Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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?

like image 727
Skilldrick Avatar asked Nov 22 '25 03:11

Skilldrick


1 Answers

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.

like image 108
meder omuraliev Avatar answered Nov 23 '25 19:11

meder omuraliev