Search code examples
htmlcsswebkitcss-floatword-wrap

floated element with negative margin causes text wrap bug?


This one looks like a text wrap bug in webkit, or did i miss something?

DOM:

<div>
  <p>
    <img src="http://static.jsbin.com/images/favicon.png">
    no sea takimata sanctus estestest Lorem ...
  </p>
</div>

CSS:

div {
  width: 200px;
}

p {
 margin-right: 32px;
 padding-left: 30px;
}

img {
 float: left;
 margin-left: -30px;
}

wrong text wrap

Demo: http://jsbin.com/onoced/1/edit

Screenshots:

Chromium 22.0.1223.0 (149385) and Chrome 21.0.1180.79 Firefox 14.0.1 Opera 12.00


Solution

  • I wouldn't say this is a bug, as you pointed out: it behaves equally in WebKit browsers. Otherwise we'd have to classify every single difference between Browser engines as bugs.

    Though there are people who already reported a similar problem to Webkit.org: http://bugs.webkit.org/show_bug.cgi?id=63074

    But this is not just limited to paragraphs, same behaviour can be also found in lists and headers.

    See example: http://jsbin.com/uzozus/1/edit

    An explanation for this behaviour in Webkit browsers is:

    If a negative margin is applied opposite a float, it creates a void leading to the overlapping of content.

    Source: http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/

    Let's apply this to your example: your image width is 16px by 16px so in order to equalise this to the negative margin of 30px we have to add 14px horizontally

      img {
        float: left;
        margin-left: -30px;
        padding:5px 14px 0 0;
      }
    

    See example: http://jsbin.com/onoced/37/edit