Search code examples
htmlcssheightbackground-color

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

  • 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.