如何向相对 Div 溢出父级添加边距以向下移动内容

How to Add Margin to Relative Div Overflowing Parent to Move Content Down

我创建了一个与父对象重叠的 div,div 之后的边距未按预期表现。我希望div之后的内容出现过高的div之后,但事实并非如此。

预期行为

expected_image

现实:

reality


这是代码:

HTML:

<div>
  <div class="hero">
    <div class="heading">
      <h1>Greg Potts' Website</h1>
      <h4>
        Software Developer / Vim-er / Bash-er
      </h4>
    </div>
  </div>
  <p>Some content next</p>
</div>

CSS:

.hero {
  height: 20vh;
  width: 100%;
  background: #272c33;
}
.heading {
  position: relative;
  top: calc(15vh);
  width: 50%;
  padding: 30px;
  margin: auto; /* horizontally center */
  background: white;
  box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);
  border-radius: 3px;
}
.heading h1, h2, h3, h4, h5, h6 { text-align: center; }

我怀疑它与 clearfix 有关,但尝试了一些解决方案,但它们没有按预期工作。

谢谢。

为了实现这一点,我会重组 HTML 元素,因为如果使用你的结构,不添加空白的 clearfix 元素是无法完成的。

相反,从 .hero 元素中取消嵌套 .heading 并为 top css 属性 使用负值会非常简单反而。

您可以另外将 .hero.heading 元素包装在一个容器中,以调整由于负 top 值而导致的左下边距。

代码如下所示:

HTML

<div>
    <div class="hero-container">
        <div class="hero"></div>
        <div class="heading">
            <h1>Greg Potts' Website</h1>
            <h4>
                Software Developer / Vim-er / Bash-er
            </h4>
        </div>
    </div>

    <p>Some content next</p>
</div>

CSS

.hero {
    height: 20vh;
    width: 100%;
    background: #272c33;
}
.heading {
    position: relative;
    top: calc(-10vh);
    width: 50%;
    padding: 30px;
    margin: auto; /* horizontally center */
    background: white;
    box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);
    border-radius: 3px;
}
.hero-container {
    margin-bottom: calc(-10vh);
}
.heading h1, h2, h3, h4, h5, h6 { text-align: center; }