Safari Margin Bug

December 8, 2006     

Since I have no time to write anything interesting, here’s a Safari CSS bug for the Google hordes (also reported to the Hyatt team at Apple).

Consider the following CSS:

p {
    margin-bottom: 10px;
.bar:last-child {
    margin-bottom: 25px;
.bar {
    background: #979FA8;
    margin-bottom: 50px;

The bug is that the .bar:last-child margin appears to override whatever is in the .bar declaration.

<div class="foo">
  <div class="bar">
    <p>Paragraph 1</p>  
    <p>Paragraph 2</p>

  <div class="bar">
    <p>Paragraph 3</p>

In this HTML the gap between the two blocks will incorrectly be displayed as 25px. In the case of vertical margins, the greatest margin should be used (aka collapsing margins). The contestants should be top margin on .bar and p as well as the bottom margins on .bar and p as well as .bar:last-child. All of the aforementioned are considered correctly except for the .bar.

There are no shortage of workarounds. The bug is fairly obscure as it is. For instance, adding specificity to the .bar selector fixes it, such as changing the selected to .foo .bar. You can also fix it by resizing the text. In the production web page that produced this bug, I noticed that reloading would fix the bug (however I can’t reproduce that in the reduced version here). I also noticed that reloading would not fix it when the Google Maps API code was on the page. Something to do with caching no doubt.

Zach says…
December 16, 2006 at 6:08AM

This doesn’t just happen with margins. You can demonstrate this bug using the ‘background’ style, for instance. All .bar:list-child styles will be applied to all .bar elements, whether they are the :last-child or not.

It is pretty funny that resizing the text fixes it.