我有以下布局。我设置了CSS,以便p
元素与第一个div
重叠。
#wrapper {
width: 600px;
margin: 0 auto;
}
.div-01 {
background: red;
height: 400px;
}
.div-02 {
background: green;
height: 200px;
}
p {
background: blue;
color: #fff;
margin: 0 100px;
padding: 100px;
position: relative;
bottom: 100px;
}

<div id="wrapper">
<div class="div-01"></div>
<p>Hello world</p>
<div class="div-02"></div>
</div>
&#13;
但我也想要它,以便在绿色div
之前没有间隙,请注意绿色div
的作用就像p
没有的位置一样已被修改。
我知道这是正常行为,但有没有办法让绿色div
在p
之后直接显示?
修改
抱歉,我应该提到我喜欢它以便在p
行为之后所有元素,好像p
还没有准确地移动了相对位置,但好像它的自然位置好像重叠了蓝色div
因此p
我也不能使用absolute
定位,因为它不清楚任何元素在真实物体中的高度
答案 0 :(得分:2)
您可以在绿色div上使用相同数量的否定margin-top
作为蓝色div的bottom
位置。
#wrapper {
width: 600px;
margin: 0 auto;
}
.div-01 {
background: red;
height: 400px;
}
.div-02 {
background: green;
height: 200px;
margin-top: -100px;
}
p {
background: blue;
color: #fff;
margin: 0 100px;
padding: 100px;
position: relative;
bottom: 100px;
}
&#13;
<div id="wrapper">
<div class="div-01"></div>
<p>Hello world</p>
<div class="div-02"></div>
</div>
&#13;
答案 1 :(得分:1)
我明白这是正常的行为,但有没有办法让绿色div在
p
之后直接出现?
是,将相对定位应用于两个元素。换句话说,为绿色div提供与其上方bottom: 100px
相同的p
。
#wrapper {
width: 600px;
margin: 0 auto;
}
.div-01 {
background: red;
height: 400px;
}
.div-02 {
background: green;
height: 200px;
position: relative;
bottom: 100px;
}
p {
background: blue;
color: #fff;
margin: 0 100px;
padding: 100px;
position: relative;
bottom: 100px;
}
<div id="wrapper">
<div class="div-01"></div>
<p>Hello world</p>
<div class="div-02"></div>
</div>
当然,这意味着div-02
以下的元素会将此元素看作原始位置。
要了解相对定位的工作方式,请参阅我的答案:Why are horizontal scroll bars shown on my website?
更新(基于评论)
......我的意思是,任何后续元素都没有差距......
在这种情况下,请删除所有相对定位,然后在margin-top: -100px
上使用p
。
#wrapper {
width: 600px;
margin: 0 auto;
}
.div-01 {
background: red;
height: 400px;
}
.div-02 {
background: green;
height: 200px;
}
p {
background: blue;
color: #fff;
margin: -100px 100px 0;
padding: 100px;
}
<div id="wrapper">
<div class="div-01"></div>
<p>Hello world</p>
<div class="div-02"></div>
</div>