'Background-color with fixed height disturbs my document flow

I need my bg color to be fixed size and I want my #second-div to start after <hr>. But this fixed height of bg-color messes up my doc flow and h1-s of the bg-div appear over my #second-div. Any thoughts how can I fix it?

I've tried using clearfix but it does no help, as bg-div has no floats...

EDIT: to specify - I need those h1-s to overflow the green bg. WORKAROUND: I've created another div just for fixed-height-bg and then gave bg-div a negative top margin. Visually it satisfies my needs, but wanted to know, if there is a simpler solution.

<head>
  <style>
    .bg-div { 
      width: 100%;
      height: 200px;
      background-color: #00FF00; 
    }
  </style>
</head>
<body>
  <div class="bg-div">
    <h1>bg-div-content</h1>
    <h1>bg-div-content</h1>
    <h1>bg-div-content</h1>
    <h1>bg-div-content</h1>
    <h1>bg-div-content</h1>
    <h1>bg-div-content</h1>
    <hr>
  </div>
  <div id="second-div">
    <h1>second div content</h1>
  </div>
</body>

codepen link with same html-css to play around



Solution 1:[1]

If you really need a fixed background color as part of the layout, I'd try an absolutely positioned div just for that purpose. See this CodePen for reference

<div class="bg-block"></div>
<div class="first-div">
  <h1>bg-div-content</h1>
  <h1>bg-div-content</h1>
  <h1>bg-div-content</h1>
  <h1>bg-div-content</h1>
  <h1>bg-div-content</h1>
  <h1>bg-div-content</h1>
  <hr>
</div>
<div id="second-div">
  <h1>second div content</h1>
</div>  
.bg-block { 
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 200px;
  background-color:#00FF00;
  z-index: -1;
}

NOTE: 1. using multiple h1s is usually discouraged, as h1 implies the top hierarchy of the content 2. using an absolute size unit for this type of layout concept is typically less flexible, so I'd suggest you consider other design approach if possible.

Solution 2:[2]

if you keep height fixed then the content is obviously going to overflow. That's not good practice do height:100% and see that it fits really well and is dynamic based on the content. Your html should be dynamic because you cannot expect the size of the content in real time.

Solution 3:[3]

It sounds like the height you're setting for bg-div is just too small to fit all the H1 elements you're putting inside it. You can make the H1 elements smaller by setting their font-size to something smaller. Alternatively, if you don't care about losing some of the content that you put inside bg-div, you can set overflow: hidden on bg-div. This will prevent the browser from displaying any content from bg-div that would otherwise be outside the bounding rectangle of the div.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bumhan Yu
Solution 2 Hadi Pawar
Solution 3 Ross Hunter