CSS相对定位和流程

时间:2016-12-09 18:14:09

标签: html css css-position

我有以下布局。我设置了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;
&#13;
&#13;

但我也想要它,以便在绿色div之前没有间隙,请注意绿色div的作用就像p没有的位置一样已被修改。

enter image description here

我知道这是正常行为,但有没有办法让绿色divp之后直接显示?

修改

抱歉,我应该提到我喜欢它以便在p行为之后所有元素,好像p还没有准确地移动了相对位置,但好像它的自然位置好像重叠了蓝色div

因此p

之后的任何元素之间基本没有差距

我也不能使用absolute定位,因为它不清楚任何元素在真实物体中的高度

2 个答案:

答案 0 :(得分:2)

您可以在绿色div上使用相同数量的否定margin-top作为蓝色div的bottom位置。

&#13;
&#13;
#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;
&#13;
&#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>