绝对定位的元素与屏幕右侧重叠,没有滚动

Absolutely positioned element overlapping the right side of the screen with no scrolling

我正在尝试绝对定位高度和宽度未知的 div,使其部分位于屏幕右侧,同时禁用向右滚动。当我尝试在屏幕的 left 侧执行此操作时,它工作得很好。但是当我在屏幕右侧尝试时,我遇到了问题。

我曾尝试使用 overflow-x 来解决这个问题,但这会使整个 div 意外消失。

.parent1 {
  position: relative;
  background-color: #ddd;
}

.child1 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #00ff00;
  left: -50px;
  top: 0;
}

.parent2 {
  position: relative;
  background-color: #ddd;
}

.child2 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  right: -50px;
  top: 0;
}

.parent3 {
  position: relative;
  background-color: #ddd;
  overflow-x: hidden;
}

.child3 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  right: -50px;
  top: 0;
}
<div class="parent1">
  <div class="child1">
    This works on the left: half of the DIV is off the screen and un-scrollable; the other half is showing.
  </div>
</div>

<div class="parent2">
  <div class="child2">
    But when I try it on the right, I'm able to scroll the screen right and see this whole DIV.
  </div>
</div>

<div class="parent3">
  <div class="child3">
    I would expect overflow-x to solve this problem, but it hides the DIV entirely.
  </div>
</div>

JSFiddle

如何才能使我的 div 位于屏幕右侧之外,同时禁用滚动?

您只需要在 body 上应用 overflow-x: hidden。如果父项本身是可滚动的,则为 parent 隐藏 overflow-x 的解决方案将起作用,否则没有什么可隐藏的。

body {
  overflow-x: hidden;
}

.parent1 {
  position: relative;
  background-color: #ddd;
}

.child1 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #00ff00;
  left: -50px;
  top: 0;
}

.parent2 {
  position: relative;
  background-color: #ddd;
}

.child2 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  right: -50px;
  top: 0;
}

.parent3 {
  position: relative;
  background-color: #ddd;
}

.child3 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  right: -50px;
  top: 0;
}
<div class="parent1">
  <div class="child1">
    This works on the left: half of the DIV is off the screen and un-scrollable; the other half is showing.
  </div>
</div>

<div class="parent2">
  <div class="child2">
    But when I try it on the right, I'm able to scroll the screen right and see this whole DIV.
  </div>
</div>

<div class="parent3">
  <div class="child3">
    I would expect overflow-x to solve this problem, but it hides the DIV entirely.
  </div>
</div>

将 child 2 的样式更改为 position: fixed

.child2 {
  position: fixed;
  width: 100px;
  height: 100px;
  background-color: #ff0000;
  right: -50px;
  top: 0;
}