Skilldrick
Skilldrick

Reputation: 70849

Why does margin-top get applied to the containing element here?

I'm sure this has been asked many times but I couldn't work out what to search for.

I have the following HTML and CSS (see jsfiddle for a live example):

<!--HTML-->
<body>
    <div id="container">
        <div id="header">
            <ul>
                <li>Item1</li>
                <li>Item2</li>
            </ul>
        </div>
    </div>
</body>



/* CSS */
#container {
    background-color: red;
    width: 400px;
    height: 200px;
    margin: auto;
}

#header ul {
    list-style: none;
    margin-top: 20px; /* I want this to be the margin at the top of the ul, not the container */
}

#header li {
    float: left;
    margin-right: 10px;
}

The problem I'm having is with the margin-top of the <ul>. It's adding space above the #container <div>, not above the <ul>. I must be missing something fundamental about CSS, because I just don't get this behaviour. Could someone enlighten me please?

Upvotes: 3

Views: 153

Answers (2)

meder omuraliev
meder omuraliev

Reputation: 186562

Due to margin collapsing, if it touches the top of the body then that's where the margin lives. Easy fix is to just rely on top padding.

Upvotes: 5

dotariel
dotariel

Reputation: 1604

Try the padding. I've also found that using a CSS reset is helpful in getting everything to behave more similarly across browsers.

http://meyerweb.com/eric/tools/css/reset/

Upvotes: 1

Related Questions