Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does div collapse with relative/absolute positioning?

I've dealt with divs collapsing on their content when using float positioning (e.g. solving with overflow:hidden), but am trying to learn absolute/relative positioning and can't figure out why the container div is collapsing. My test case:

<html>
  <head>
    <style type="text/css">
      body {
        background-color:#eee;
      }

      #content {
        margin:0 auto;
        position:relative;
        border:1px solid red;
        width:800px;
        display:block;
        background-color:white;
      }

      #header {
        border:1px solid black;
        background-color:#777;
        color:white;
        width:800px;
        position:absolute;
        left:0;
        top:0;
      }

      #leftcol {
        position:absolute;
        border:1px solid black;
        background-color:#ddd;
        width:200px;
        top:100px;
        left:0;
      }

      #rightcol {
        position:absolute;
        top:100px;
        left:205px;
        border:1px solid black;
        background-color:#ddd;
        width:500px;
      }

    </style>
    <title>CSS Positioning Example 1</title>
  </head>

  <body>
    <div id="content">

      <div id="header">
        <h1>The Awesome Website</h1>
      </div>

      <div id="leftcol">
        <h2>About</h2>
        <p>
        This website is so awesome because it was made by someone
        and that is really all there is to it.  There.
        </p>
      </div>

      <div id="rightcol">
        <p>This is where I'm going to put some real body text so that it goes
        on and on for a while and so I can get a sense of what happens when
        the text in the paragraph keeps going and the box containing it keeps
        going on as well.
        </p>
      </div>

    </div>

  </body>
</html>

What's going on here? Why does the red-bordered content div collapse even though it contains the other divs?

like image 713
mix Avatar asked Sep 20 '11 03:09

mix


2 Answers

It is because all of its content is styled as position:absolute. This takes those elements out of flow and (layout-wise) it's like they don't even exist. Consider using position:relative to position the content.

like image 56
Joseph Marikle Avatar answered Sep 23 '22 23:09

Joseph Marikle


You really need to read these articles at A List Apart

CSS Positioning 101

CSS Floats 101

Your question is why the div with red borders don't expand to it's content. As Joseph said the problem is that you take the elements out of the document flow. Positioning an element absolutely make the element's position independent from it's parent and siblings.

I fixed your code using CSS float property. Take a look here.

I highly recommend you read those articles.

like image 28
Mohsen Avatar answered Sep 24 '22 23:09

Mohsen