CSS 内容 div 越过固定导航栏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20840365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:27:50  来源:igfitidea点击:

Content div going over fixed navbar

css

提问by CuriousCabbage

I've got a stylesheet where the intention is to have a fixed navbar which stays at the top of the screen no matter how far you scroll down. For this I've just used position:fixed;- but when I actually scroll down, the #contentdiv overrides it and goes straight over the top (so the navbar stays at the top of the page but is underneath the content div.)

我有一个样式表,目的是让一个固定的导航栏保持在屏幕顶部,无论你向下滚动多远。为此,我刚刚使用过position:fixed;- 但是当我实际向下滚动时,#contentdiv 会覆盖它并直接越过顶部(因此导航栏位于页面顶部但位于内容 div 下方。)

I haven't done any serious CSS coding in years, so I'm a bit rusty - it's probably a very simple solution, so apologies for being so trivial!

我已经好几年没有做过任何严肃的 CSS 编码了,所以我有点生疏——这可能是一个非常简单的解决方案,所以为这么琐碎而道歉!

style.css

样式文件

body {
    margin:0;
    background:#eeeeee;
}

#navbar {
    background-color:#990000;
    position:fixed;
    width:100%;
    height:50px;
    text-align:center;
    vertical-align:middle;
    line-height:50px;
    top:0px;
}

#navbar a {
    color:#fff;
}

#content {
    background:#eeeeee;
    margin-top:50px;
    width:100%;
}

#feed {
    background: #fff;
    position:absolute;
    left:22%;
    width:776px;
}

Pages are structured like this:

页面结构如下:

<body>
    <div id="navbar"><?php include core/navbar.php; ?></div>
    <div id="content">
        <div id="feed">
            CONTENT
        </div>
    </div>
</body>  

回答by DaniP

In order to fix this you need the property z-indexdefined by W3that specify the level of the element. Try this:

为了解决这个问题,您需要z-indexW3 定义的属性指定元素的级别。尝试这个:

#navbar {
  background-color:#990000;
  position:fixed;  
  z-index:1; /*Add this*/
  width:100%;
  height:50px;
  text-align:center;
  vertical-align:middle;
  line-height:50px;
  top:0px;
}

回答by Osprey Eagle

If you're using Bootstrap 4, the .navbar background is clear and can be covered by some elements. Setting the z-index won't work. Use a background color, e.g., .bg-white.

如果您使用的是 Bootstrap 4,.navbar 背景是清晰的,并且可以被一些元素覆盖。设置 z-index 不起作用。使用背景颜色,例如,.bg-white。

<nav class="navbar fixed-top navbar-expand-sm navbar-light bg-white">