Jonny Barnes
Jonny Barnes

Reputation: 535

position: absolute inside position: relative causes content to overlap

I have a main element I have set to position: relative. This contains two divs that I then apply position: absolute on. This then causes the header and footer that sandwich the main element to then bump up against each other. How can I stop this?

Using floats and clearing the footer seems to give the two column layout I want. But I'm not sure how “sturdy” a solution that is and what'll happen on IE6/7.

Code on codepen.

Upvotes: 0

Views: 3273

Answers (1)

Marc Audet
Marc Audet

Reputation: 46785

All you elements in main are absolutely positioned, so main's height computes to zero, so the bottom edge of the header is next to the top edge of the footer. If you add a height to main you will open up space between the header and footer.

Given the following HTML:

<header>Header</header>
<main>
  <div id="text">
    <p>Some text</p>
  </div>
  <div id="links">
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
    </ul>
  </div>
</main>
<footer>
  <p>Footer</p>
</footer>

You can realize a two-column layout using floats as shown in the following CSS:

main {
position: relative;
height: auto;
overflow: auto;
border: 1px solid blue;
}

#text {
float: left;
width: 500px
}

#links {
float: left;
width: 400px;
}

You need to set overflow: auto on your main container to contain the floats (equivalent to clearing them).

Also, make sure that the widths of the floated element are not too wide or else they will wrap to a 2nd line if the screen size is too narrow.

See demo at http://codepen.io/anon/pen/gGsjd

Footnote: Using overflow:auto versus clear:both

I tend to use overflow: auto but in some cases the the clear property is what is needed. At some point, read up about "block formatting contexts" at http://www.w3.org/TR/CSS2/visuren.html#block-formatting The reasons to pick one approach over the other are a bit subtle and the choice depends on the details of the layout that you are trying to achieve, how it behaves in a responsive manner and so on.

Upvotes: 3

Related Questions