htmlcssoverflowclearfix

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


I have created a div that overlaps its parent, and the margins after the div are not behaving as expected. I expect the content following the div to appear after the overlowing div, but it's not.

Expected Behavior :

expected_image

Reality :

reality


Here is the code:

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; }

I suspect it has something to do with clearfix, but have tried a few solutions and they haven't worked as intended.

Thanks.


Solution

  • I would go with restructuring the HTML element in order to achieve this, as it is can not be done without adding blank clearfix element if working with the structure your set.

    Instead it would be really simple to un-nest the .heading from the .hero elements and use negative value for the top css property instead.

    You can additionally wrap the .hero and .heading elements in a container to adapt the bottom margin left as a result of a negative top value.

    The code would look like the following:

    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; }