html - CSS相对定位和流程

标签 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>

但我也希望绿色 div 之前没有间隙,请注意,绿色 div 的作用类似于 p 的位置 尚未修改。

enter image description here

我知道这是正常行为,但是有什么方法可以让绿色 div 直接出现在 p 之后吗?

编辑:

抱歉,我应该提到我希望这样,p 之后的所有 元素都可以表现得就像 p 没有一样。没有完全按照相对定位移动,但就好像它的自然位置与蓝色 div

重叠

所以在p之后的任何元素之间基本上没有间隙

我也无法使用绝对定位,因为不清楚任何元素在真实事物中的高度

最佳答案

您可以在绿色 div 上使用与蓝色 div 的 bottom 位置相同数量的负 margin-top

#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;
}
<div id="wrapper">
  <div class="div-01"></div>
  <p>Hello world</p>
  <div class="div-02"></div>
</div>

关于html - CSS相对定位和流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066485/

相关文章:

css - 如何使这张 table 居中?

javascript - 如何将外部 CSS 文件分配给 javascript 构造的 SVG 对象?

css - 当容器的位置为 :relative 时, float 元素消失在背景后面

html - 固定位置使元素的代码部分消失

html - rmarkdown 网站和 HTML 依赖项中的 Shiny 应用程序

html - CSS 选择器优化

javascript - 如何保留同步期间发生的 DBChangeTracker 中的更改?

javascript - 脚本类型 ="text/html"的现代用途是什么?这个例子是否被认为是很好的用途?

css - 从顶部开始的绝对位置,水平居中的 div

html - 为什么 height 100% 对绝对定位元素有效?