【问题标题】:Overflow-y auto clips a child element horizontallyoverflow-y 自动水平裁剪子元素
【发布时间】:2021-11-20 12:05:19
【问题描述】:

我有一个父元素

position: relative;
overflow-y: unset;

和一个带有

的子元素
position: relative;
left: -70px;

这看起来不错。但是在父元素上设置overflow-y: auto 后,子元素的左侧被剪裁了。我不明白为什么会这样。如何在不剪切子项的情况下向父项添加垂直(自动)滚动条?

const checkbox = document.getElementById('checkbox');
const right = document.querySelector('.right');
const value = document.getElementById('value');

checkbox.addEventListener('change', (event) => {
  const overflowY = event.target.checked ? 'auto' : 'unset';
  right.style.overflowY = overflowY;
  value.innerText = overflowY;
});
.right {
  background-color: red;
  width: 100px;
  height: 300px;
  position: relative;
  left: 200px;
  /* toggle overflow-y between unset and auto */
  overflow-y: unset;
}

.two {
  background-color: blanchedalmond;
  top: 50px;
  height: 50px;
  position: relative;
  left: -70px;
}
<body>
  <p>
    Whenever overflow-y changes from unset to auto the yellowish block gets clipped.
  </p>
  <p>
    <input id="checkbox" type="checkbox"> overflow-y: <span id="value">unset</span>
  </p>

  <div class="right">
    <div class="two right-content"></div>
  </div>
</body>

【问题讨论】:

    标签: html css scroll


    【解决方案1】:

    const checkbox = document.getElementById('checkbox');
    const right = document.querySelector('.right');
    const value = document.getElementById('value');
    
    checkbox.addEventListener('change', (event) => {
      const overflowY = event.target.checked ? 'auto' : 'unset';
      right.style.overflowY = overflowY;
      value.innerText = overflowY;
    });
        .right {
          background-color: red;
          width: 100px;
          height: 300px;
          position: relative;
          left: 200px;
          /* toggle overflow-y between unset and auto */
          overflow-y: auto;
          /*Try This*/
          display: inline-table;
        }
    
        .two {
          background-color: blanchedalmond;
          top: 50px;
          height: 50px;
          position: relative;
          left: -70px;
        }
        <body>
          <p>
            Whenever overflow-y changes from unset to auto the yellowish block gets clipped.
          </p>
          <p>
            <input id="checkbox" type="checkbox"> overflow-y: <span id="value">unset</span>
          </p>
    
          <div class="right">
            <div class="two right-content"></div>
          </div>
        </body>

    【讨论】:

    • 唯一的变化是display: inline-table;?很有趣。
    • 它对你有用吗?
    • 至少效果更好。很高兴能解释为什么inline-table 的行为不同以及究竟有什么不同。我还不确定它是否完全解决了我原来的问题。
    猜你喜欢
    • 2012-10-23
    • 2021-01-02
    • 1970-01-01
    • 2011-07-19
    • 2019-02-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多