Introduction:

Have you ever gazed up at the night sky and felt a sense of wonder? The stars twinkling like diamonds against the dark canvas of the universe is a truly breathtaking sight. In this tutorial, we'll show you how to recreate this magical effect on your website using CSS and JavaScript.
The CSS:
First, let's create the dark sky background and add some stars using CSS:
body {
  background-color: #2f4f7f; /* Dark blue color */
}

.stars {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url('https://picsum.photos/200/300'); /* Replace with your image */
  background-size: cover;
  background-position: center;
  transform: perspective(500px);
  transform-style: preserve-3d;
}

.star {
  position: absolute;
  top: calc(var(--star-top) * 1%);
  left: calc(var(--star-left) * 1%);
  width: 2px;
  height: 2px;
  background-color: #fff;
  border-radius: 50%;
  animation: twinkle calc(var(--star-twinkle-duration) * 1s) infinite;
}
The JavaScript:
Next, let's add some JavaScript to generate random values for the star positions and animations:
JavaScriptconst root = document.documentElement;

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

root.style.setProperty('--star-top', getRandomNumber(1, 100));
root.style.setProperty('--star-left', getRandomNumber(1, 100));
root.style.setProperty('--star-twinkle-duration', getRandomNumber(3, 8));

setInterval(() => {
  root.style.setProperty('--star-top', getRandomNumber(1, 100));
  root.style.setProperty('--star-left', getRandomNumber(1, 100));
  root.style.setProperty('--star-twinkle-duration', getRandomNumber(3, 8));
}, 5000);
Conclusion:
With these simple steps, you can create a mesmerizing night sky effect on your website. The CSS creates the dark sky background and adds some static stars, while the JavaScript generates random values for the star positions and animations, creating a dynamic and changing effect. You can adjust the code to customize the effect to your liking. Happy coding!Full Code Demo