html - 具有固定标题的可滚动内容

标签 html css scrollbar

我想要一个带有固定标题和可滚动内容的容器。这是我为此设置的 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/

相关文章:

html - 带有边距和填充的跨度

javascript - jquery点击事件;调用特定函数(如果可用)

animation - CSS3 Keyframes 如何让图像圈在不动的情况下运行

html - 设置 td 的宽度在此表中不起作用

css - CSS 中出现水平滚动条的原因是什么?

javascript - 单击它时如何弹出一个 float /粘性窗口?

javascript - 旋转方法使所有东西旋转

html - 如何让容器 div 占满屏幕的 100%?

html - 带有媒体查询的水平滚动条问题

angular - PrimeNG 的 Turbo Table 在 IE11 和 Edge 浏览器上显示滚动条,即使 [可滚动] 输入字段已禁用