html - 如何强制粘性导航栏“覆盖”其内容
问题描述
假设我有一个如下导航栏:
* {
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>
正如您在滚动之前看到的那样,粘性导航栏最初位于内容段落的上方。但是,如果 navbar 类从 更改sticky
为fixed
,那么 navbar 会覆盖内容(就像我想要的那样),但它不会随着容器滚动,因为它已被转换。
如何强制粘性导航栏将内容放在其下方,以便它始终像其后内容的覆盖一样?
如果上述情况不可行,那么如何强制固定导航栏在转换后的容器中与用户一起滚动?请注意,我想避免与此答案类似的事情(这是我目前正在使用的),因为它会导致滚动时固定容器上的抖动运动。
解决方案
使用 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>
推荐阅读
- angular - 单击谷歌地图角度中的标记时如何为地图添加不透明度
- python - 如何使用python重试SQL更新语句直到它成功
- python - 使用 django 框架流式传输 opencv 框架并不适用于所有
- angular - 角度变量值的变化不会反映在 DOM 中
- reactjs - 有没有办法使用 react-jsonschema-form 将枚举值之一设为强制?
- reactjs - 如何使用 React Hooks 单独切换手风琴面板?
- networking - 在ns-2中实现VANET拥塞控制算法
- c# - 解决 IQueryable 没有为 EF 实现 IDbAsyncQueryProvider
- python - 从 Pandas Dataframe 中的第一个非 NaN 条目导出日期
- c# - 覆盖DataTable c#中的列,添加空列