6

I have some HTML that looks like this:

<div class="TheContainer">

 <div class="TheData">this is some text inline-block with clear</div>
 <div class="TheData">this is some other text inline-block but not clearing</div>

</div>

The CSS looks like this:

.TheContainer{
 margin:20px 20px;
 background:red;}

.TheData{
 display:inline-block;   
 clear:both;
 background:yellow;
 padding:5px 5px;
 margin:10px 10px;}

I'm using inline-block so that the TheData divs wrap nicely around their content instead of extending the total width of TheContainer. I'm also using clear:both so that these TheData divs get stacked one above the other.

However, it seems that clear:both doesn't apply when elements are set to inline-block. The JSFiddle here demonstrates this.

How do I use inline-block AND make the divs stack vertically?

Thanks.

2 Answers 2

7

clear is only for clearing float

To get the effect you want, put float:left on .TheData. You will most probably also want an element below those div.TheDatas with clear but no float to make sure the container renders with the correct height.

Updated fiddle

1
  • Why would you use float on a display: inline-block? You lose some of the functionality of inline-block doing that.
    – Steven
    Commented May 29, 2015 at 20:47
3

I think what you want is the one clear-fix to rule them all.

I don't think you want display: inline-block; because it's actually working the way it supposed to. You might be better off with float: left; clear: both; on your inner elements and the clear-fix on the container element:

CSS:

TheContainer{
     margin:20px 20px;
     padding:10px 10px;
     background:red;
     clear:both;
}

.TheData{
    float:left;
    clear: both;
    background:yellow;
    padding:5px 5px;
    margin:10px;
}

/* For modern browsers */
.cf:before,
.cf:after {
    content:"";
    display:table;
}
.cf:after {
    clear:both;
}
/* For IE 6/7 (trigger hasLayout) */
.cf {
    zoom:1;
}.

<div class="TheContainer cf">

    <div class="TheData">smaller</div>
    <div class="TheData">smaller a</div>
    <div class="TheData">smaller a b</div>
    <div class="TheData">smaller a b c</div>
    <div class="TheData">smaller a b c d</div>
    <div class="TheData">this is some other text inline-block but not clearing</div>
</div>

jsFiddle

1
  • Hey, thanks :) Yeah, I agree, it is more complex, but it comes with the benefit of not having to add an extra DOM element. Thanks for the upvote even though you prefer the other answer!
    – tiffon
    Commented Dec 11, 2012 at 3:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.