views:

119

answers:

3

I've always heard that margins in CSS will collapse when next to each other, so that settings two elements to have 40px all around will only result in 40px between them.

Is this an old way to render CSS, as in does it not work this way anymore?

This is the HTML and CSS. I can't seem to get the margins to collapse:

Relevant HTML

<div id="header">
    <div id="mainNav" class="navBar">
        <a id="homeLink" class="navBarLinks">Home</a>
        <a id="aboutLink" class="navBarLinks">About</a>
        <a id="articlesLink" class="navBarLinks">Articles</a>
        <a id="portfolioLink" class="navBarLinks">Portfolio</a>
        <a id="contactLink" class="navBarLinks">Contact</a>
        <a id="rssLink" class="navBarLinks">RSS</a>
    </div>
    <div class="infoBar"></div>
</div>

The CSS

#header { width: 100% }
.navBar {
    width: 100%;
    height: 24px;
    background-color: #1a1a1a;
    border: 0px solid #404040
}
#mainNav { border-bottom-width: 2px }
.navBarLinks {
    display: block; float: left;
    height: 11px;
    margin: 0 30px;
    background: url(/images/STORMINKsprite.png) no-repeat;
    text-indent: -9999px
}

Thanks for the advice!

+3  A: 

I don't know what currently happens on IE, but if you float two elements and have margin-right: 30px; on the first, and margin-left: 30px; on the second, there will be 60px between the two. So, I believe it doesn't collapse.

theIV
+6  A: 

Your answer can be found in the CSS2.1 specification recommendation:

In CSS 2.1, horizontal margins never collapse.

So given the code you've written, you'll get 60px between each link - 30px for each element's margin.

What you probably want to do is use 15px horizontal margins, and then add 15px of horizontal padding to the containing element.

Shog9
+2  A: 

If you have 2 elements with 40px margin on all 4 sides, then the gap between those two elements will be 80px.

GaVrA