Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: DIV containing no height on float set

assume we have this code:

<div id='upperDiv' style='min-height:200px;border: 1px solid #000000;'>
     <div id='rightDiv' style='float:right;width:75%;'>
       content1
     </div>  
     <div id='leftDiv' style='float:left;width:25%;'>
       content2
     </div>
</div>
<div id='lowerDiv' style='height:50px;border: 1px solid #000000;margin-top:5px;'>
   content3
</div>

When content of rightDiv and leftDiv passes the 200px height (the min height) upperDiv doesn't grow, so its content overlaps the lower div. If I remove the float attribute of the large content it grows and there will be problem. But I don't know which Div (rightDiv or leftDiv) passes 200px height. How can I fix this?

Thanks

like image 600
Ariyan Avatar asked Oct 24 '10 19:10

Ariyan


People also ask

Why does div have 0 height?

It has zero height because the content inside it is floated. Floated elements are ignored when calculating the height of their parent. This can be easily solved. Setting its overflow property to "hidden" will force it to wrap around floated elements.

How do you make div height not expand with content?

Answer: Use the CSS display Property You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).

How do I make an element float inside a div?

One solution is to float the parent element as well as the child elements. The parent element is the div with the container class so add float:left to it.


2 Answers

Set #upperDiv any of the following:

overflow: hidden;
width: 100%;

or

float: left;
width: 100%;

or create a rule using CSS pseudo-elements (IE8+ compatible) like this

#upperDiv:after {
  content: "";
  display: table;
  clear: both;
}

Best solution
Creating a reusable class rule like the following.

.group:after {
  content: "";
  display: table;
  clear: both;
}

Now you can apply it to anything that needs this same functionality. For example...

<div id='upperDiv' class="group" ... >

P.S. If you require IE 6/7 compatibility, checkout this post.

like image 143
jessegavin Avatar answered Sep 18 '22 17:09

jessegavin


This is intentional as floats are designed for things like images in paragraphs (where multiple paragraphs can wrap around the image).

Complex Spiral has a fuller explanation as to why and Ed Elliot describes a number of approaches to making containers expand around floats. I find the overflow: hidden approach works best in most situations.

like image 45
Quentin Avatar answered Sep 22 '22 17:09

Quentin