如何仅使用 CSS 使内容进入滚动条?

god*_*rry 5 html css

我知道有各种用于自定义滚动的 JS 库,但我相信现代浏览器最好采用更一致和可预测的本机行为。我假设我将nice在 Chrome/Edge(Blink)acceptable中使用滚动条,在 FF 中使用它们自己简单的颜色/大小自定义,我不会关心其他浏览器。

在此处输入图片说明 我现在面临的唯一问题是 - 我希望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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Fyo*_*dor 3

做overflow: overlay你想做的事。但请考虑到此功能不是标准。Edge 还有另一个属性-ms-overflow-style: -ms-autohiding-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);
}
Run Code Online (Sandbox Code Playgroud)

工作示例(在 Chrome 中测试)

  • 请添加工作小提琴并确保您的答案是正确的。 (2认同)
  • 在 chrome 114 中删除 (2认同)