0

so I am trying to make a divs height automatically adjust based on the height of the content inside it. This is my current work:

<div id="content">
    <div id="item"></div>
    <div id="item"></div>
    <div id="item"></div>
    <div id="item"></div>
    <div id="item"></div>
    <div id="item"></div>
    <div id="item"></div>
</div>

#content {
margin: 0px auto;
margin-top: 10px;
border: 1px solid;
width: 920px;
}

#item {
display: block;
width: 220px;
height: 250px;
border: 1px solid;
margin-left: 6px;
margin-bottom: 5px;
float: left;
}

I have discovered that when I am NOT applying 'float: left' to the 'item' divs that it does work, however when I do apply float: left the height is not being set based on the content inside. Any idea on how to fix this?

Duncan Palmer
  • 2,865
  • 11
  • 63
  • 91

4 Answers4

1

It is because the items are floated. When an element is floated, it removes itself from the normal flow of the document. That's why the parent div collapses when you float the div items.

You should use clear fix.

One way is to add a div after the last div item, and add clear:both style in it.

Another way is to use some "hack" to the parent div:

.parent:before,
.parent:after {
    content: "";
    display: table;
} 
.parent:after {
    clear: both;
}
qtgye
  • 3,580
  • 2
  • 15
  • 30
1

You have applied a static height to #item, remove this property and it will auto-size for height.

josh.thomson
  • 905
  • 9
  • 25
1

Apply overflow: hidden; to #content or clear the floating.

Also every id you use have to be unique in the document. It's not good to do use ID Like you did here:

<div id="item"></div>
<div id="item"></div>

Use the class attribute for such things.

Demo with overflow: http://jsfiddle.net/9WSFf/1/

Secondly, you could do something like this:

#content:after
{
    content:"";
    clear:left;
    display: block;
}

Demo:http://jsfiddle.net/9WSFf/2/

Nico O
  • 13,762
  • 9
  • 54
  • 69
0

Please check this JS FIDDLE

CSS

#content {
  margin: 0px auto;
  margin-top: 10px;
  border: 1px solid;
  width: 920px;
 }
.clear {
  clear:both;
 }
 #item {
    display: block;
    width: 220px;
    height: 250px;
    border: 1px solid;
    margin-left: 6px;
    margin-bottom: 5px;
    float: left;
  }

Please apply clear:both after last item id div

Gunaseelan
  • 2,494
  • 5
  • 36
  • 43
Yogesh Sharma
  • 2,017
  • 1
  • 15
  • 33