我想要一个带有固定标题和可滚动内容的容器。这是我为此设置的 HTML 和 CSS
HTML:
<div class="container">
<div class="header">Header</div>
<div class="content">
<ul>
<li>Content</li>
<li>Content</li>
...
</ul>
</div>
<div>
CSS:
.container {
margin-top: 200px;
}
.header {
position: fixed;
width: 100%;
height: 20px;
background-color: blue;
color: white;
}
.content {
padding-top: 20px;
height: 250px;
background-color: grey;
overflow: auto;
}
Codepen 链接:http://codepen.io/robkom/pen/XKMQGM
如您所见,标题是固定的并与滚动条重叠(可见时)。我想要的是滚动条将标题推到左侧(就像它对内容所做的那样),并且在我滚动时仍保持在容器的顶部。
固定元素从正常文档流中移除并相对于视口(viewport)定位,所以我不确定使用 position: fixed
的解决方案是否可行,但有什么方法可以实现这个结果?
最佳答案
这里有一个技巧,在 header 中使用包装器。
我在标题上强制滚动,根据内容制作包装器大小,然后我简单地将标题增加 50px 以确保覆盖所有不同浏览器的滚动条尺寸,并在包装器上使用相同的量来推送它回到视野。
这样做,您就不必担心单独的滚动条宽度调整(或使用脚本)。
我还将 header 更改为绝对位置,以便它与容器一起定位,但如果需要,您当然可以切换回固定位置。
已更新
Firefox 不显示小高度的滚动条,因此添加 margin/padding-top
如下所示使其工作
html, body {
margin: 0;
}
.container {
position: relative;
overflow-x: hidden;
margin-top: 0px;
}
.header {
position: absolute;
overflow-y: scroll;
width: calc(100% + 50px);
height: 20px;
margin-top: -20px; /* Firefox doesn't show scrollbar for small */
padding-top: 20px; /* heights, so these two lines make it work */
}
.header .wrapper {
width: calc(100% - 50px);
height: 100%;
background-color: red;
color: white;
}
.content {
padding-top: 20px;
height: 200px;
background-color: grey;
overflow: auto;
}
<div class="container">
<div class="header">
<div class="wrapper">
Header
</div>
</div>
<div class="content">
<ul>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
</ul>
</div>
<div>
关于html - 具有固定标题的可滚动内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38106266/