2016-11-07 42 views
1

假設我有這個代碼。使用css的定位元素

<div class="big_div" > 
    <div class="small_div" id="small_div_1" ></div> 
    <div class="small_div" id="small_div_2" ></div> 
    <div class="small_div" id="small_div_3" ></div> 
    <div class="small_div" id="small_div_4" ></div> 
</div> 

.big_div{ 
    width:1000px; 
    height:1000px; 
    background-color:green; 
} 
.small_div{ 
    width:50px; 
    height:50px; 
    position:absolute; 
    top:100px; 
    background-color:red; 
} 
#small_div_1{ 
    left:200px; 
} 

好了,我有4個綠色面紅色正方形,第一方(#small_div_1)是從表面的左側200像素,並且所有都是從100像素表面的頂部上。我可以如何讓其他3個正方形放在他們以前的兄弟(旁邊#small_div_2 - 250px,左邊#small_div_3 - 300px,左邊#small_div_4 - 350px)旁邊,而不需要分別定位每個正方形。因爲當我有4個方格時這不是問題,但是當我有100個方格時,這是一個問題。有沒有辦法使用Sass或類似的東西,也許是JavaScript?

+1

使用Flexbox的。太棒了。看看這個:** [Flexbox指南](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)** – jherax

+1

在任何情況下,絕對定位都在桌子外面如果您正在尋找具有未知數量元素的可擴展解決方案。 – Serlite

+0

[用CSS定位另一個元素的元素]可能的重複(http://stackoverflow.com/questions/32830701/position-elements-around-another-with-css) – jherax

回答

0

你可以做這樣的事情。使用CSS:flexbox。

.big_div { 
 
    width: 1000px; 
 
    height: 1000px; 
 
    display: flex; 
 
    background-color: green; 
 
    direction: column; 
 
    justify-content: space-around; 
 
} 
 
.small_div { 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: red; 
 
    margin-top: 100px; 
 
    border: 1px solid black; 
 
}
<div class="big_div"> 
 
    <div class="small_div" id="small_div_1"></div> 
 
    <div class="small_div" id="small_div_2"></div> 
 
    <div class="small_div" id="small_div_3"></div> 
 
    <div class="small_div" id="small_div_4"></div> 
 
    <div class="small_div" id="small_div_5"></div> 
 
    <div class="small_div" id="small_div_6"></div> 
 
</div>

+0

謝謝,我的解決方案存在一些問題,但現在這是所有固定的(忘記刪除「位置:絕對」爲「small_div」) – Matija

+0

很高興幫助 – Sreekanth

0

我覺得有更漂亮的解決方案,但你可以用青菜就此別過:

@for $i from 0 through 99 { 
    #small_div_#{$i} { 
    left: (200 + 50 * $i)px; 
    } 
}