Abddoo
Abddoo

Reputation: 63

How to make floated div container fit to the div height?

I have a div container #parent and a div child #child who's child of the parent div .

The #child div contain text and he is floated left, the problem is that I want the #parent div to fit the height of the #child` div what ever the height is with keeping the float property also .

    #parent{
       background: red;
       height: auto;
    }

    #child{
       float:left;
    }
    <div id='parent'>
        <div id='child'>
           <p>Some text Some text Some text</p>
        </div>  
    
    </div>

Here is a Jsfiddle

Upvotes: 4

Views: 1793

Answers (4)

Prime
Prime

Reputation: 3625

Method :1

 #parent{
       background: red;
       height: auto;
       overflow:auto
    }

    #child{
       float:left;
      }

http://jsbin.com/yufezamofo/3/

Method:2

 #parent{
       background: red;
       height: auto;
display:table
    }

    #child{
       float:left;
      display:table-cell;
      }

http://jsbin.com/yufezamofo/2/

Upvotes: 2

Denny Smith
Denny Smith

Reputation: 113

Use clearfix.

.clearfix:after {
             visibility: hidden;
             display: block;
             font-size: 0;
             content: " ";
             clear: both;
             height: 0;
    }
.clearfix { 
   display: inline-block; 
    }
            /* start commented backslash hack \*/
    * html .clearfix { 
     height: 1%; 
    }
    .clearfix { 
    display: block; 
    }
      /* close commented backslash hack */

http://jsfiddle.net/XgErJ/463/

Upvotes: 0

seńor fiksie
seńor fiksie

Reputation: 51

Check out the Demo

One way to do it is with ":after" selector.

HTML

<div id='parent'>

    <div id='child'>
       <p>Some text Some text Some text</p>
    </div>  

</div>

CSS

#parent{
   background: red;
}
#parent:after {
   content:'';
   display:block;
   clear: both;
}
#child{
   float:left;
}

Upvotes: 0

j08691
j08691

Reputation: 207901

Add overflow:auto to the parent:

#parent {
    background: red;
    height: auto;
    overflow:auto;
}
#child {
    float:left;
}

jsFiddle example

When you float the child, the parent collapses because it's acting as if the child occupies no space. Adding the overflow rule restores the behavior that you're after.

Upvotes: 7

Related Questions