Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't my simple CSS margins collapsing?

Tags:

html

css

margin

web

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!

like image 401
Ian Storm Taylor Avatar asked Sep 05 '09 02:09

Ian Storm Taylor


2 Answers

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.

like image 129
Shog9 Avatar answered Sep 18 '22 12:09

Shog9


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.

like image 43
theIV Avatar answered Sep 20 '22 12:09

theIV