2016-06-15 71 views
1

我創建了一個繁星點點的夜間動畫,但想知道是否有人有更好的方式將div「隨機」放在只有CSS?另外,我也很難反應。感謝您的時間!只是想學習。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; 
} 
+0

什麼是你想要做什麼呢? –

+0

尋找一種更簡單的方法來編碼星型配置,而不是重複n次(x)次 – user3393940

回答

1

此刻的完整代碼這是不可能的純CSS(我希望的鈣(RAND)成爲東西)。您使用的解決方案與任何解決方案一樣好,如果您希望星星聚集在較小的屏幕類型上,您可能需要考慮使用百分比。

1

不幸的是,目前在CSS中是不可能的。

但是,如果您願意從CSS更改爲LESS,則可以爲您的星星賦予隨機值。通過用back-ticks包裝JavaScript表達式,可以在LESS中插入JavaScript,如this post所示。

這裏是給你的DIV#星-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.

0

不與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 

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