简体   繁体   中英

parent container encompassing the child elements

Im not sure why my float isn't clearing so that a child container will stay inside the parent container.

Have a look at this jsfiddle to see what i mean. I want the .shadow-wrapper div to encompass all the other elements that follow it. How can I get the parent container to encompass the child elements?

Use this:

.shadow-wrapper {
    background-color: red;
    clear: both;
    overflow:hidden;
}

To enclose floated elements you can use any the following:

float:left;
overflow:hidden;
display:table;
display:inline-block;
display:table-cell;

Other solution using the :after method:

.shadow-wrapper:after {
    clear:both;
    content:" ";
    display:block;
}

As you can see from this codes, clear both doesnt need to be applied everywhere, only after the last element which is floated, and therefore we can use the after method which simulates this.

http://jsfiddle.net/7wja6/

One option is to add float:left; to .shadow-wrapper .

.shadow-wrapper {
    background-color: red;
    clear: both;
    float: left;
}

http://jsfiddle.net/kMGQC/1/

A general rule for using floats and clears is that if you float one item, you should probably float all of its siblings too. If that seems problematic, you can add an extra div as the last child and clear both with that div, that should fix your issue.

<div class="wrapper">
  <div class="floating-thing">Hellllllooooo</div>
  <div class="non-floating-thing">Weeeeeeee</div>
  <div class="clearfix"></div>
</div>

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