0

我试图理解css定位。我想要完成的是:我希望当我设置一个div位置时,div在它之后,改变第一个div移动的位置,而不是重叠它们。让我们举个例子:

HTML

<div class="wrap">
    <div class="box1">
    </div>
    <div class="box2">
    </div>
    <div class="box3">
    </div>
</div>

CSS

.wrap{
    position: absolute;
    background-color:yellow;
    width:500px;
    height:600px;
    margin:0 auto;
}

.box1,.box2,.box3{
    position: relative;
    width:450px;
    height:150px;
    margin:0 auto;
}
.box1{background-color:red; top: 100px;}
.box2{background-color:green;}
.box3{background-color:blue;}

现在,当我设置时,例如top:100pxon box1,它100px从顶部开始,但box2仍然box3存在。我希望当我top在其中一个上设置位置时,div它们“遭受”设置位置的变化,而不是重叠或被其他div我尝试过的重叠,position: relative但它没有达到我的目标。

对不起,如果我解释得更好,我很难用英语解释。

4

4 回答 4

1

使用 margin-top 而不是 top。Top/Bottom/Left/Right 改变了通常的位置,因此它不会影响其余部分。边距也会影响其余部分。

http://jsfiddle.net/eux4C/3/

.box1{background-color:red; margin-top: 100px;}
于 2013-06-08T15:41:19.510 回答
1

top属性(asleft和)rightbottom用于定位绝对元素。
将此属性赋予元素可能会赋予它绝对行为。
定位一个你应该使用的相对元素margin-top

是一个工作小提琴

于 2013-06-08T15:43:05.263 回答
1

csstop属性只能用于具有位置的元素absolute(如聊天中所述:-)。

对于相对定位的元素,您应该使用margin-top如下属性:

.box1 {background-color:red; margin-top: 100px;}

这是一个工作小提琴:http: //jsfiddle.net/IrvinDominin/eux4C/4/

于 2013-06-08T15:51:16.633 回答
0

听起来您真的想保留标准盒子模型,而不是忽略它。

不要设置位置:相对,并使用 padding -top 或 margin-top 来添加额外的空间。

于 2013-06-08T15:43:09.250 回答