我正在尝试创建一个具有动态高度的标题,并在滚动时固定在页面顶部(在整个滚动过程中可见)。动态高度的原因是由于浏览器调整大小,因此当标题中的文本换行时,标题的高度会增加。
因此,增加的高度在开始滚动之前覆盖了部分主体。虽然我已经尝试将 padding-top: YYpx
添加到主体,但是当 header 的高度发生变化时,它会覆盖主体的元素。基本上,我想要有两个连续的容器,但不互相重叠,并且在滚动第二个容器时,第一个容器会粘在顶部。
我想使用整个页面滚动,而不是仅在第二个容器中使用滚动条。如果这是不可能的,那么在第二个容器内滚动也可以被接受作为答案,前提是第二个容器的内容将根据第一个容器的新高度向下移动。
我已经为此苦苦挣扎了几天,我尝试过 this ,但是 .header-container
覆盖了部分背景,这不是我想要的。
我试图使用导航栏作为标题,但事实证明它确实限制了我可以放入其中的内容,因此我制作了一个自定义标题来修复顶部。
之前(不使用 CSS @media): https://jsfiddle.net/q19of4j6/1/
之后(我尝试使用 CSS 手动移动第二个容器): https://jsfiddle.net/q19of4j6/
调整上面的 jsfiddle 的大小以查看问题。
使用@media来移动容器对我来说是不可行的。
我现在拥有的:
CSS
.custom-navbar {
padding: 0.5rem 1rem;
}
body > main {
padding-top: 112px;
}
@media (max-width: 1153px) {
body > main {
padding-top: 136px;
}
}
@media (max-width: 955px) {
body > main {
padding-top: 160px;
}
}
HTML
<body>
<header>
<!--Fixed navbar-->
<nav class="custom-navbar fixed-top navbar-light bg-light">
<!-- Contents in the header that I wish to keep at the top while scrolling-->
</nav>
</header>
<main role="main">
<div class="container-fluid">
<table class="table table-striped table-bordered dataTable" cellspacing="0"
width="100%" role="grid">
<!--Contents of table, and contents that will move while scrolling-->
</table>
</div>
</main>
</body>
我希望在调整浏览器宽度时(尚未开始滚动),main
内的内容将根据 header
的新高度进行移动。
但是现在,当header
高度增加时,它会覆盖main
的部分内容。
我仍然希望标题固定在页面顶部,并且 main
中的内容可以使用整页滚动条滚动。
最佳答案
尽你所能see here ,没有简单的方法可以动态固定标题高度。大多数解决方案涉及设置定义的标题高度或 JS。
IMO,最简单的解决方案是使用 position:sticky
而不是 position:fixed
:
https://www.codeply.com/go/ElHS24d2vT
<header class="sticky-top">
<!--Fixed navbar-->
<nav class="custom-navbar navbar-light bg-light">
<div>
whateverlalallala
</div>
</nav>
</header>
<main role="main">
<div class="container-fluid">
<table class="table table-striped table-bordered dataTable" cellspacing="0" width="100%" role="grid"></table>
<p style="background:red">1</p>
<p style="background:blue">2</p>
<p style="background:orange">3</p>
<p style="background:green">4</p>
</div>
</main>
关于html - 在开始滚动之前如何不隐藏具有动态高度的固定顶部标题下的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408641/