Pixel.Deficient Pixel.Deficient - 5 years ago 116
HTML Question

How to fit a div's height to wrap around its floated children

I have a div wrapped around two children, one floated left and the other right. I want to put a border and background around the children, but the div has 0 height since it doesn't resize to fit the children.

Here is an example of it in action:
http://jsfiddle.net/VVZ7j/17/

I want the red background to go all the way down. I've tried height:auto, but that didn't work.

Any and all help would be appreciated, thanks.

P.S. I don't want to use any javascript if that's possible.

Answer Source

This is a common issue when working with floats. There are several common solutions, which I have ordered by personal preference (best approach first):

  1. Use the ::after CSS pseudo element. This is know as the 'clearfix', and works IE8 and up. If you need compatibility with earlier versions of IE, this answer should help. Example.

    .parentelement::after {
        content: "";
        display: table;
        clear: both;
    }
    
  2. Add the two floats into a container with the CSS attribute overflow: auto or overflow: hidden. However, this approach can cause issues (e.g. when a tooltip overlaps the edges of the parent element a scrollbar will appear). Example.

    <div style="overflow: auto">
        <div style="float: left"></div>
        <div style="float: left"></div>
    </div>
    
  3. Add a set height to the parent element. Example.

    <div style="height: 200px">
        <div style="float: left"></div>
        <div style="float: left"></div>
    </div>
    
  4. Make the parent element a float. Example.

    <div style="float: left">
        <div style="float: left"></div>
        <div style="float: left"></div>
    </div>
    
  5. Add a div after the floats with clear: both. Example.

    <div style="float: left"></div>
    <div style="float: left"></div>
    <div style="clear: both"></div>
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download