Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed inline-block div with negative margin-right and shifting float: what's special about -4px?

This is strange. I'm trying to have a fixed-width div next to a right-floated div, and I don't want to reorder the divs (because this is distributed theme). So I'm playing with negative margin-right on the fixed div, and I get what seems to me strange: if it's -4px or less, then the float moves to the side; otherwise, it stays below.

Play with the live demo with code at jsbin, which has this:

<style>
  .container {
    width: 200px;
    height: 200px;
  }
  .box {
    width: 100px;
    height: 100px;
  }
  .one {
    margin-right: -4px; /* If <= -4, .two box shifts up */
    display: inline-block;
  }
  .two {
    float: right;
  }
</style>
  <div class="container">
    <div class="box one"></div>
    <div class="box two"></div>
  </div>

Can someone explain the mystery? What's special about the number -4 in this case?

like image 607
huyz Avatar asked Oct 25 '22 06:10

huyz


1 Answers

4px just happens to be the width of a "space" at that font-size.

If you change the font-size of #container to say, 32px, it breaks.

Sensible ways to fix this include:

  • Remove margin-right: -4px and then remove the whitespace between the divs in the HTML.
  • Don't use display: inline-block. Instead, float: left the left div, and float: right the right div.
    • If you're worried about it breaking when you don't have a fixed height on the container, then you must clear the floats. Use overflow: hidden on the container, or use clearfix.
    • With overflow: hidden (use this unless you have specific problems)
    • With clearfix
like image 89
thirtydot Avatar answered Oct 27 '22 09:10

thirtydot