块元素的绝对定位使其与它的兄弟元素一致

时间:2014-05-13 04:05:42

标签: css html5 css-position

我在尝试绝对定位标题内的h3(或任何其他块元素)元素时出现了意外行为。由于绝对定位是相对于第一个非静态父元素进行的,因此h3元素应该相对于容器在窗口顶部对齐。但由于某种原因,它与它的兄弟导航元素一致。这是标记:

<!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>

1 个答案:

答案 0 :(得分:0)

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

有你的问题:

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

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

您的H3属于main-header的一部分而且是疯狂的margins

尝试这样的事情:

见这里: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;
}

见这里:http://jsfiddle.net/aLSXn/3/