gpt4 book ai didi

html - 如何将粘性导航栏强制为 "overlay"其内容

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:42 25 4
gpt4 key购买 nike

假设我有一个如下所示的导航栏:

* {
box-sizing: border-box;
}

html,
body {
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
}

body {
display: flex;
justify-content: center;
}

.container {
width: 100px;
height: 100%;
transform: translateX(50px);
/* An example transform (I can't use position: fixed) */
background-color: green;
overflow-y: scroll;
}

.navbar {
width: 100%;
height: 50px;
background-color: rgba(255, 255, 0, 0.5);
top: 0;
}

.navbar.sticky {
position: -webkit-sticky;
position: sticky;
}

.navbar.fixed {
position: fixed;
}
<div class="container">
<div class="navbar sticky">
</div>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>

正如您在滚动之前看到的,粘性导航栏最初位于内容段落上方。但是,如果导航栏类从 sticky 更改为 fixed,那么导航栏会覆盖内容(就像我想要的那样),但它不会随容器滚动,因为它被转化了。

我如何强制粘性导航栏将内容置于其下方,以便它始终表现得像覆盖其后的内容?

如果以上不可能,那么我如何强制固定导航栏在转换后的容器中随用户滚动?请注意,我想避免类似于 this answer 的情况(这是我目前正在使用的),因为它会导致滚动时固定容器上的抖动。

最佳答案

从带有 margin-bottom 的导航栏中减去导航栏的高度即可。

* {
box-sizing: border-box;
}

html,
body {
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
}

body {
display: flex;
justify-content: center;
}

.container {
width: 100px;
height: 100%;
transform: translateX(50px);
/* An example transform (I can't use position: fixed) */
background-color: green;
overflow-y: scroll;
}

.navbar {
--navbarheight: 50px;
width: 100%;
height: var(--navbarheight);;
background-color: rgba(255, 255, 0, 0.5);
top: 0;
}

.navbar.sticky {
position: -webkit-sticky;
position: sticky;
margin-bottom: calc(0px - var(--navbarheight)); /* or -50px in other words */
}

.navbar.fixed {
position: fixed;
}
<div class="container">
<div class="navbar sticky">
</div>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>

关于html - 如何将粘性导航栏强制为 "overlay"其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com