0

我想要达到的目标

图片是我想要实现的。基本上,我正在尝试制作一个包装器 div,并能够根据父包装器最左边部分的左边距在其中放置可变数量的 div。

我希望能够这样说:

.div1 { margin-left:5%; }
.div2 { margin-left:30%; }
.div3 { margin-left:85%; }

并实现图中所见。然而,我注意到(我原以为会发生),div 不愿意合作;当我添加 a 时float:left,它们似乎相互添加了边距(因为 div2margin-left:30%除了 5% 的左边距和 10% 的宽度外,还得到了 a ,这使得 div2 出现在距离包装器最左边的 45% 处。

我意识到我可以只考虑以前的边距,并将 div2 的左边距设置为 30%-15%=15% 并得到正确的结果,但我想知道是否有办法做到这一点左边距?

4

2 回答 2

1

不要漂浮它们;相反,将它们绝对定位在某个位置,以便它们在某种意义上“重叠”;边距将以您想要的方式将它们分开。

例子:

.green {background-color: green; position: absolute}
.one {width:10%; margin-left:5%}
.two {width:20%; margin-left: 30%}
.three {width:10%; margin-left: 85%}

演示在:

http://jsfiddle.net/Mu4GU/

于 2013-04-12T08:26:03.437 回答
0

您可以尝试使用浮动而不使用绝对位置。

HTML

<div id="page">
<div id="box1">10%</div>
<div id="box2">25%</div>
<div id="box3">15%</div>

CSS

#page{width:100%;height:200px; background-color:#000;}
#box1{height:200px; background-color:red; width:10%; margin-left:5%;float:left;}
#box2{height:200px; background-color:green; width:25%; margin-left:15%;float:left;}
#box3{height:200px; background-color:blue; width:15%; margin-left:30%;float:left;}

演示:http: //jsfiddle.net/pDxXB/

于 2013-04-12T08:53:08.723 回答