Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating elements within a div, floats outside of div. Why?

Say you have a div, give it a definite width and put elements in it, in my case an img and another div.

The idea is that the content of the container div will cause the container div to stretch out, and be a background for the content. But when I do this, the containing div shrinks to fit the non-floating objects, and the floating objects will be either all the way out, or half out, half in, and not have any bearing on the size of the big div.

Why is this? Is there something I'm missing, and how can I get floated items to stretch out the height of a containing div?

like image 449
DavidR Avatar asked Jan 14 '10 04:01

DavidR


People also ask

Why is my Div not floating right?

You need to float the blocks on the right side not push them over with left margin. Set them to float: right and they'll kick up where you want them. Until you float the elements they want to take up the full width of their parent container.

How do you float in a div?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.


1 Answers

The easiest is to put overflow:hidden on the parent div and don't specify a height:

#parent { overflow: hidden } 

Another way is to also float the parent div:

#parent { float: left; width: 100% } 

Another way uses a clear element:

<div class="parent">    <img class="floated_child" src="..." />    <span class="clear"></span> </div> 

CSS

span.clear { clear: left; display: block; } 
like image 92
Doug Neiner Avatar answered Oct 08 '22 11:10

Doug Neiner