2016-11-07 77 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; 
    } 
}