4

I created a starry night animation but was wondering if anyone had a better way to place divs "randomly" with only CSS ??? Also, I'm having difficulty with responsiveness as well. Thank you for your time! just trying to learn.

check the complete code at http://codepen.io/anon/pen/MeeYWO?editors=1100

#star-bl:nth-of-type(5) {
    left: -350px;
    top: 225px;
}

#star-bl:nth-of-type(6) {
    left: 750px;
    top: 250px;
}

#star-bl:nth-of-type(7) {
    left: -450px;
}

#star-sm:nth-of-type(8) {
    left: -225px;
}

#star-sm:nth-of-type(9) {
    left: 500px;
}

#star-sm:nth-of-type(10) {
    left: -100px;
}
user3393940
  • 51
  • 1
  • 1
  • 6

3 Answers3

3

It's not possible in pure CSS at the moment (I'm hoping for calc(rand) to become a thing). The solution you are using is as good as any, you may want to consider using percentages if you want the stars to cluster on a smaller screen type.

GeorgeButter
  • 2,521
  • 1
  • 29
  • 47
1

Unfortunately that is not possible at the moment in CSS.

However, if you would be willing to change from CSS to LESS, you could give your stars random values. It's possible to insert JavaScript into LESS by wrapping the JavaScript expression with back-ticks as shown in this post.

Here's an example for giving your div #star-bl a random left value from 1 to 100.

#star-bl {
    @random-margin: `Math.random() * 100`;
    left: @random-margin * 1px;
}

You would still need to give every star a separate block inside the LESS file, but it would give your stars different positions every time you visit the page.

Here's a link to a guide for using LESS.

Community
  • 1
  • 1
Zentryn
  • 544
  • 2
  • 12
0

Not with vanila CSS but you can use a CSS pre-processor such as Less or Sass to generate random numbers for you at compile time.

Here's how you could do it in Sass using its random instance method.

@import compass
body
  background: black

.star
  width: 10px
  height: 10px
  position: absolute
  font-size: 10px
  color: white

@for $i from 1 through 500
  .star:nth-child(#{$i})
    top: random(1000) + px
    left: random(1000) + px

DEMO: http://codepen.io/moob/pen/dXXGdy

Moob
  • 14,420
  • 1
  • 34
  • 47