Vadym
Vadym

Reputation: 548

CSS float container doesn't wrap around it's children, clearing the children doesn't work

Why doesn't div with class "items" wrap around its "item"s? Applying clear: both to the children doesn't help. The section also does not wrap around "item"s.

.items {
    background: #ff0;
    width: 1000px;
    display: block;
}

.item1,
.item2,
.item3 {
    width: 290px;
    height: 350px;
    float: left;
    margin-left: 23px;
    margin-top: 80px;
    background-color: #cbcbcb;
}
<section>
  <div class="items">
    <div class="item1">
      <h3>Php testing</h3>
    </div>
    <div class="item2">
      <h3>Jquery testing</h3>
    </div>
    <div class="item3">
      <h3>Another one</h3>
    </div>
  </div>
</section>

Upvotes: 1

Views: 127

Answers (3)

Victor Radu
Victor Radu

Reputation: 2292

Or just try .items{overflow:hidden}

Upvotes: 0

bjb568
bjb568

Reputation: 11498

What you want is a clearfix, an element (or pseudo-element) after the items. It's common practice to give the parent element the class "clearfix". Here's a simple pseudo-element method for the CSS:

.clearfix::after {
    content: ''; /* To create the pseudo-element */
    display: table; /* This is the shortest way of making it work here */
    clear: both; /* This actually pushes it below and expands the parent */
}

Upvotes: 1

Joshua Whitley
Joshua Whitley

Reputation: 1186

When an item is floated, it's taken out of the normal "flow" of the document so containers ignore it being there and don't wrap around it. There are several "float clearing" solutions to make the container wrap floated items. This one is the old standard:

HTML

<section>
    <div class="items">
        <div class="item1">
            <h3>Php testing</h3>
        </div>
        <div class="item2">
            <h3>Jquery testing</h3>
        </div>
        <div class="item3">
            <h3>Another one</h3>
        </div>
        <div class="clear">&nbsp;</div>
    </div>
</section>

CSS

.clear {
    clear: both;
    height: 0;
    visibility: none;
}

Another option is using the CSS :after pseudo-element but this only works in more modern browsers:

.items:after {
    content: ".";
    display: block;
    clear: both;
    height: 0;
    visibility: collapse;
}

Upvotes: 1

Related Questions