水平滚动条显示右侧有溢出内容但左侧没有?

新手上路,请多包涵

我有一个元素 position: absolutebody 的一部分从左侧 左侧。

演示小提琴

 * {
  overflow: visible;
}

#test {
  position: absolute;
  height: 100px;
  width: 100px;
  left: -50px;
  background-color: lime;
}
 <div id="test"></div>

我希望水平滚动条应该出现,允许将文档滚动到元素的隐藏部分,但事实并非如此。所以,我对这个案例有一些疑问:

  1. 为什么会这样,为什么滚动条没有出现(它在右侧的对称布局下工作正常)?
  2. 有没有可能让它出现并 向左滚动
  3. 我错过了关于滚动条的任何非常基本的东西吗?

原文由 Vasily Liaskovsky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 708
1 个回答

为了显示滚动条,父元素必须具有设置的宽度。对于水平滚动条,在父项上使用属性 overflow-x:scroll; 将使滚动条出现。

听起来与此问题类似: Div with horizontal scrolling only

尝试回答您的问题:

  1. 使用 right: -50px 时会出现滚动条,因为 HTML 文档的标准流程是从左到右。 CSS 推出了#test div,浏览器能够继续向右呈现。此时看起来 div 的一部分可能在主体之外,但事实并非如此。 HTML 页面上可见的所有内容都必须在正文中。

  2. 在父容器或正文上使用 CSS display: rtl; 会使滚动条向左滚动而不是向右滚动,但是如果你对正文执行此操作,整个文档现在将从右向左工作,改变所有在页。我建议使用具有 CSS 属性 display: rtl; 的父元素。

 #parent {
  position: static;
  height: 100px;
  width: 100px;
  overflow-x: scroll;
  overflow-y: hidden;
  background-color: red;
  direction: rtl;
}

#test {
  width: 100px;
  height: 100px;
  background-color: lime;
  position: relative;
  left: -50px;
}
 <div id="parent">
  <div id="test">
  </div>
</div>

当然,这意味着 #parent 元素始终完全可见。如果这不是想要的,那么替代方法 设置 direction:rtl; 但确保您想要正确显示的任何内容然后在具有 CSS direction: ltr; 的包装 div 中以恢复正常流程:

 body {
  direction: rtl;
  overflow: scroll;
}

#allOtherContent {
  direction: ltr;
  width: 100%;
  background-color: red;
}

#test {
  width: 100px;
  height: 100px;
  background-color: lime;
  position: absolute;
  left: -50px;
}
 <div id="test"></div>
<div id="allOtherContent"></div>
  1. 当另一个元素中的元素太大而无法容纳时,会出现滚动条。为此,浏览器需要知道父元素的确切大小以确定测试元素太大,因此需要滚动。

In my example the #parent has a width of 100px , the same as the #test div, however the #test div has been pushed left 50px 相对于 #parent #test 150px 父级现在有溢出的内容,CSS overflow-x:scroll; 添加了我们的水平滚动条。

有关溢出和滚动条如何工作的更多信息,请参见此处: https ://developer.mozilla.org/en/docs/Web/CSS/overflow。

希望能帮助回答您的问题。

原文由 Andrew Stalker 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题