2

Codepen Example

I'm trying try to float an element to the right in an inline-element block but I'm noticing some strange behavior.

In the codepen link above, the first example shows that the .box div is wrapping around the floated element. I thought that you need to use a clearfix hack to make sure that a floated element's parent would properly contain it but that's not the case here. Also, for some reason the floated element is creating some extra vertical space beneath its parent div (see the blue gap in the codepen example). I also noticed that if you put some inline text next to the floated element, then the gap disappears (second example in codepen link).

Is there a reason why the inline-block parent element doesn't need to be cleared? Also, why is there extra space that appears below the parent div and how do you remove it?

.container {
  background-color: blue;
  text-align: center;
}
.box {
  background-color: red;
  display: inline-block;
  width: 300px;
}
.float {
  float: right;
  line-height: 40px;
}
<div class='container'>
  <div class='box'>
    <div class='float'>Float Element</div>
  </div>
</div>
</br>
<div class='container'>
  <div class='box'>
    Some text
    <div class='float'>Float Element</div>
  </div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
Copernicus
  • 291
  • 1
  • 2
  • 13
  • inline-block reset the block formating context ( such as: table, inline-table, position:absolute or fixed, overflow:hidden,..) so the behavior you notice is the right one ;) see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context and eventually : https://www.w3.org/TR/CSS2/visuren.html#block-formatting (i can turn this into an answer if you think it is. extra space comes from the br tag btw – G-Cyrillus Sep 23 '16 at 16:00
  • @GCyrillus can you explain a bit more? How would resetting the formatting context affect clearing behavior? And when I mention the extra space, I'm talking about the blue gap in the first html element. If you inspect the first .box div, it's height is 40 pixels, but the height of its .container parent is 44 pixels. The gap I'm talking about is the 4 extra pixels between the .box and .container divs. – Copernicus Sep 23 '16 at 16:05
  • Inline/inline-block elements just don't behave well for trying to make block like structures. I would suggest not using inline-block for stuff like this. – Leeish Sep 23 '16 at 16:06
  • @Copernicus: [It kinda just does.](http://www.w3.org/TR/CSS21/visudet.html#root-height) There is no real explanation for this, other than ["historical reasons"](http://stackoverflow.com/questions/9943503/why-does-css2-1-define-overflow-values-other-than-visible-to-establish-a-new-b/11854515#11854515). – BoltClock Sep 23 '16 at 16:07
  • The blue gap is explained by the very last paragraph of the page in the first link in my previous comment (scroll all the way to the very bottom). – BoltClock Sep 23 '16 at 16:15

0 Answers0