Question

I got an unexpected behavior when trying to absolute position an h3(or any other block element) element inside header. Since absolute positioning is made relative to the first non-static parent element, the h3 element should have aligned at the top of the window relative to the container. But for some reason it aligns with it's sibling nav element. Here is the markup:

<!DOCTYPE html>
<html>
<head>
<title>Sometitle</title>

<style type="text/css">
* {
    margin:0;
    padding:0;
}

html, body {
    width:100%;
    position:relative;
    background:lightgray;
}

#container {
    width:100%;
    position:relative;
}

#main-header {
    display:block;
}

#main-header #logo {
    position:absolute;
    top:0;
    left:0;
}

#main-header #main-nav {
    display:block;
    background:gray;
    margin:5em 6em;
}

#main-header #main-nav ul {
    list-style:none;
}

#main-header #main-nav .main-nav-link {
    display:inline-block;
}

#main-header #main-nav .main-nav-link a {
    display:inline-block;
    padding:0.8em 1em;
    text-decoration:none;
    color:white;
    font:bold 1em arial;
}

</style>
</head>
<body>
<div id="container">
    <header id="main-header">
        <h3 id="logo">Some logo</h3>

        <nav id="main-nav">
            <ul>
                <li class="main-nav-link"><a href="#">Nav1</a></li>
                <li class="main-nav-link"><a href="#">Nav2</a></li>
                <li class="main-nav-link"><a href="#">Nav3</a></li>     
            </ul>       
        </nav>  
    </header>
</div>
</body>
</html>
Was it helpful?

Solution

#main-header #main-nav {
    margin:5em 6em;
}

There's your problem:

<header id="main-header">
    <h3 id="logo">Some logo</h3>

    <nav id="main-nav">
        <ul>...

Your H3 is part of main-header with crazy margins.

Try something like this instead:

See here: http://jsfiddle.net/aLSXn/3/

HTML:

<div id="container">
    <header id="main-header">
        <h3 id="logo">Some logo</h3>
        <nav id="main-nav">
            <ul>
                <li class="main-nav-link"><a href="#">Nav1</a></li>
                <li class="main-nav-link"><a href="#">Nav2</a></li>
                <li class="main-nav-link"><a href="#">Nav3</a></li>     
            </ul>       
        </nav>  
    </header>
</div

CSS:

* {
    margin:0;
    padding:0;
}

html, body {
    width:100%;
    background:lightgray;
}

#container {
    width:100%;
}

#main-header {
    display:block;
}

#logo {
    position:absolute;
    top:0;
    left:0;
}

#main-nav {
    display:block;
    background:gray;
    margin:5em 6em;
}

#main-nav ul {
    list-style:none;
}

#main-nav .main-nav-link {
    display:inline-block;
}

#main-nav .main-nav-link a {
    display:inline-block;
    padding:0.8em 1em;
    text-decoration:none;
    color:white;
    font:bold 1em arial;
}

See here: http://jsfiddle.net/aLSXn/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top