我有一个页面,当我滚动内容时,我希望导航栏总是出现在页面的顶部。我可以通过使用以下CSS添加来实现这一点:
.navbar {
position: fixed; /* Set the navbar to fixed position */
top: 0; /* Position the navbar at the top of the page */
width: 100%;
overflow: hidden;
}
.container-main {
width: 97%;
margin-right: 40px;
margin-left: 5px;
padding-right: 5px;
padding-left: 0px;
min-height: 75vh; /* will cover the 75% of viewport */
overflow: hidden;
display: block;
position: relative;
padding-bottom: 125px; /*height of your footer*/
margin-top: 30px;
z-index:-1
}
问题是,一旦我添加了z-index:-1
,主内容就失去了被点击的能力。如果没有z-index:-1
,则主容器的内容将滚动到导航栏的顶部而不是后面。我需要做什么才能使导航栏保持在顶部,滚动导航栏下的内容,并保持单击主容器中项目的能力?下面是_layout页面的简化版本,所有这些都驻留在该页面中:
<body>
<header>
<div class="navbar navbar-inverse" id="edadTopNavigation">
<div class="container-fluid app-navbar">
</div>
</div>
</header>
<div class="container-main">
<main role="main">
@RenderBody()
</main>
</div>
<footer style="position:relative;top:0">
<div>
</div>
</footer>}
</body>
我试着对这种情况做了一个简单的沙箱,我对导航栏进行了如下编码:
#nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
color: fff; /* For testing */
background-color: #333; /* For testing*/
padding: 1rem; /* For testing*/
z-index: 100;
}
并制作了一个简单的容器,里面有一个主元素,并在里面添加了一堆链接和段落,以测试我是否可以点击链接&;选择段落或不选择段落。
容器的样式:
.container {
background-color: orangered; /* For testing*/
max-width: 1200px;
height: 700vh; /* To make the container super long to test clickability it */
margin: 5rem auto; /* To center the container */
z-index: -50;
}
左:0;
在导航栏样式,看看它是否会工作。
只需对导航栏使用更高的Z索引即可。并且主容器没有在导航栏的顶部滚动。您的代码很好,但是,您需要将main元素推到navbar下面一点。看一看这段代码:
null
.navbar {
position: fixed;
/* Set the navbar to fixed position */
top: 0;
/* Position the navbar at the top of the page */
width: 100%;
overflow: hidden;
z-index: 2;
background-color: #fff;
border-bottom: 1px solid #ddd;
padding: 20px;
}
.container-main {
position: relative;
top: 50px;
width: 97%;
margin-right: 40px;
margin-left: 5px;
padding-right: 5px;
padding-left: 0px;
min-height: 75vh;
/* will cover the 75% of viewport */
overflow: hidden;
display: block;
position: relative;
padding-bottom: 125px;
/*height of your footer*/
margin-top: 30px;
z-index: 1;
}
<html>
<body>
<header>
<div class="navbar navbar-inverse" id="edadTopNavigation">
<div class="container-fluid app-navbar">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
</div>
</header>
<div class="container-main">
<main role="main">
@RenderBody()
</main>
</div>
<footer style="position:relative;top:0">
<div>
</div>
</footer>
</body>
</html>