CSS 随机 div 放置和响应

CSS random div placement & responsiveness

我创建了一个星夜动画,但想知道是否有人有更好的方法来放置 div "randomly" 只有 CSS ???另外,我也很难响应。感谢您的时间!只是想学习。

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;
}

目前在纯 CSS 中是不可能的(我希望 calc(rand) 成为现实)。您使用的解决方案与任何解决方案一样好,如果您希望星星聚集在较小的屏幕类型上,您可能需要考虑使用百分比。

遗憾的是,目前 CSS 无法做到这一点。

但是,如果您愿意从 CSS 更改为 LESS,您可以给星星随机值。可以通过用反引号包裹 JavaScript 表达式来将 JavaScript 插入 LESS,如 this post.

所示

这是一个示例,用于为您的 div #star-bl 提供一个从 1 到 100 的随机左值。

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

您仍然需要在 LESS 文件中为每个星星分配一个单独的块,但每次访问该页面时,它都会为您的星星提供不同的位置。

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

不适用于 vanila CSS,但您可以使用 CSS 预处理器,例如 Less or Sass 在编译时为您生成随机数。

这是在 Sass 中如何使用它的 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

演示:http://codepen.io/moob/pen/dXXGdy