【问题标题】:How to make content go under scrollbar with CSS only?如何仅使用 CSS 使内容位于滚动条下?
【发布时间】:2020-02-11 18:15:45
【问题描述】:

我知道自定义滚动有多种 JS 库,但我相信对于现代浏览器来说,最好使用更一致和可预测的原生行为。我假设我将在 Chrome/Edge(Blink) 中拥有 nice 滚动条,在 FF 中拥有 acceptable 并具有它们自己简单的颜色/尺寸自定义,我不会关心其他浏览器。

我现在面临的唯一问题是 - 我希望 li 元素位于滚动条下方。我试图通过transform: translateX(15px)/margin-right: -15px/right: -15px/overflow: overlay 将内容移动到它下面,但没有任何帮助(虽然overflow:overlay<body/> 完成了这项工作,但它对内部容器没有帮助)。

在没有 JS 的情况下实现所需行为的任​​何技巧?

*::-webkit-scrollbar-track {
  background-color: transparent;
}

*::-webkit-scrollbar {
  background-color: transparent;
  transition: .3s;
}

*:hover::-webkit-scrollbar {
  width: 15px !important;
}

*::-webkit-scrollbar-thumb {
  border-radius: 10px;
  border: 2px solid #444;
}

ul {
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 70vw;
  overflow-y: scroll;
  background: linear-gradient(to top, #c6ffdd, #fbd786, #f7797d);
}

li {
  cursor: pointer;
  height: 40px;
  transition: background .2s;
  display: block;
}

li:hover {
  background: rgba(255, 255, 255, 0.4);
}

ul:after {
  content: "Scroll ↧";
  color: white;
  letter-spacing: 10px;
  position: fixed;
  left: 50%;
  top: 50%;
  font-size: 40px;
  line-height: 1;
  transform: translateX(-50%) translateY(-50%);
  mix-blend-mode: difference;
}

body {
  background: #12c2e9;
  background: #c471ed20;
  background: #444;
  justify-content: center;
  display: flex;
  padding: 0;
  margin: 0;
}
<ul>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>

【问题讨论】:

标签: html css


【解决方案1】:

overflow: overlay 可以满足您的需求。但请注意,此功能不是standard。此外,Edge 还将拥有另一个属性 -ms-overflow-style: -ms-autohiding-scrollbar; to hide scrollbar。还要在 Firefox 中仔细测试。

overflow 属性应该放在body 元素上,所以滚动条覆盖在ul 的顶部。

body {
  padding: 0;
  margin: 0;
  overflow: overlay;
}

ul {
  margin: 0;
  padding: 0;
  background: linear-gradient(to top, #c6ffdd, #fbd786, #f7797d);
}

Working sample(在 Chrome 中测试)

【讨论】:

  • 请添加工作小提琴并确保您的答案正确。
  • @AkhilAravind 你是对的伙伴,这个带有overflow: overlay 的解决方案仅在设置在正文上时才有效,而我需要在任何溢出的内容上使用它——在我的情况下是&lt;ul/&gt;
  • @Fyodor 谢谢,但是当设置在&lt;body/&gt;以外的元素上时这不起作用@
  • @Fyodor 我编辑了初始代码,这样我想要实现的目标会更加明显
猜你喜欢
  • 2021-08-11
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多