固定导航栏覆盖的间距元素

时间:2015-04-15 02:37:33

标签: html css

我经常遇到很多固定导航栏的问题,即当我有一个固定的导航栏时,如何给它下面的元素一些边距,以便固定的导航栏不覆盖那个元素?

我只是想知道除<br>标记和margin-top之外是否还有更优雅的方法。

示例代码如下:

HTML code:

    <nav>
        I AM NAVBAR
    </nav>
    <br><br>
    <div>

    </div>

CSS代码:

* {
                padding: 0;
                margin: 0;
            }

            nav {
                height: 50px;
                width: 100%;
                background: #444;
                color: #fff;
                text-align: center;
                font-weight: bold;
                font-family: verdana;
                position: fixed;
                top: 0;
                left: 0;
            }

            div {
                height: 500px;
                width: 100%;
                background: tomato;
            }

Fiddle此处。

2 个答案:

答案 0 :(得分:1)

修复了屏幕视口的相对位置。您可以在body标签上设置上边距或填充,并使值>> =导航栏高度。

body {
    margin-top: 50px; /*or padding*/
}

http://jsfiddle.net/5k5mxcn1/1/

答案 1 :(得分:1)

CSS中有一个理论,你只应用底边距。 http://csswizardry.com/2012/06/single-direction-margin-declarations/

因此,为了保持模块化,您可以创建一个包装类:

<nav class="nav__wrapper">
    <div class="nav__content">
        Navigation
    </div>
</nav>

<p>Text content</p>

的CSS:

.nav__wrapper {
    height: 30px;
    margin-bottom: 10px // breathing room
}

.nav__content {
    background: #dadada;
    height: 30px;
    line-height: 30px;
    position: fixed;
    width: 100%;
}

小提琴:http://jsfiddle.net/wv53qLwz/

相关问题