【问题标题】:CSS random div placement & responsivenessCSS 随机 div 放置和响应性
【发布时间】:2021-06-20 20:00:02
【问题描述】:

我创建了一个星夜动画,但想知道是否有人有更好的方法来仅使用 CSS 来“随机”放置 div?另外,我的反应能力也有困难。感谢您的时间!只是想学习。

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

【问题讨论】:

  • 你到底想做什么?
  • 寻找一种更简单的方法来对星形位置进行编码,而不是重复 nth-of-type (x) 次数
  • 这是一个杂乱无章的沙箱,但它可以工作......使用 JS 和动画侦听器在动画的每次迭代中为“100%”关键帧分配随机值。 codepen.io/ashleedawg/pen/qBBKKeg

标签: html css animation responsive


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    不幸的是,目前这在 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.

    【讨论】:

      【解决方案3】:

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

      这是在 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

      【讨论】:

        猜你喜欢
        • 2012-07-03
        • 2018-06-30
        • 1970-01-01
        • 2011-06-13
        • 2015-02-28
        • 1970-01-01
        • 2016-05-01
        相关资源
        最近更新 更多