我试图同时实现两种样式,一种包括粘性位置,另一种包括粘性元素的父级:
此外,导航栏位于开头部分的中间高度
这里有一个代码片段可以清楚地说明这一点,有两列,一列用于解决问题的两个方面:
body {
margin: 0px 10px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
font-size: 10px;
}
.bottom {
height: 50px;
background-color: lightblue;
margin: 10px 0px;
}
.content {
height: 200vh;
background-image: linear-gradient(red, yellow);
}
section.left header {
display: grid;
grid-template-rows: 1fr 1fr auto;
gap: 10px;
height: 100vh;
border: 1px solid blue;
}
nav {
position: sticky;
top: 0px;
}
<section class="left">
<header>
<h1>
either I have the "bottom" element at the bottom of the screen view...
</h1>
<nav>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
</nav>
<div class="bottom">bottom</div>
</header>
<div class="content">content</div>
</section>
<section class="right">
<h1>
...or I have the navbar that stick through the entire website. But how to have both ?
</h1>
<nav>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
</nav>
<div class="bottom">bottom</div>
<div class="content">content</div>
</section>
如果导航栏是 body 的直接子元素(或者任何具有网站高度的元素,如我的示例中的
<section>
),则很容易使导航栏贯穿整个网站,并且很容易拥有 bottom
如果页面顶部出现的所有内容(包括导航栏)都位于屏幕底部,则元素放置在屏幕底部。
但是一个阻碍了另一个:底部元素需要包装器,而包装器会阻止导航栏粘在整个网站上。这是我的问题!
我不觉得有一个解决方案可以让导航栏粘在它的祖父母上(在这种情况下,因为我知道有时这是可能的),所以也许最好找到一个解决方案,让
bottom
元素位于屏幕底部视图?
对于粘性导航栏
<div id="navbar">Navbar</div>
.sticky {
position: fixed;
top: 0;
width: 100%;
}
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
<div id="bottom">bottom</botton>
.bottom{
position: fixed;
bottom: 0;
left: 0;
width: 100vw;
}