简体   繁体   中英

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

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.

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;
}

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/

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM