【问题标题】:CSS: Make Absolute item in Overflow-Y always fill 100% of Scroll HeightCSS:使Overflow-Y中的绝对项目始终填充滚动高度的100%
【发布时间】:2021-06-16 04:17:55
【问题描述】:

我想让这个绝对定位的栏填充 100% 这个溢出容器的滚动高度并动态更改(如果可能的话)。

<div id="container">
  <div id="item"></div>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
</div>
#container {
  height: 300px;
  overflow-y: scroll;
  background-color: #333;
  position: relative;
}

#item {
  position: absolute;
  left: 50px;
  width: 2px;
  background-color: lightgreen;
  height: 100%;
}

https://codepen.io/springer268/pen/oNZJrjN

// 旁注 在我的用例中不起作用的 Hacky 解决方案包括使其位置固定,或使其绝对到上面的另一个 div。它必须相对于这个容器(缩放问题+其他东西。)并且实际上改变了高度。我真的很想在这里避免使用 JS(使用 React 会变得很时髦)。

谢谢

【问题讨论】:

    标签: css


    【解决方案1】:

    我会创建一个#container-inner 元素并将内容放入其中。

    或者这就是您所说的“hacky”解决方案?

    #container {
      height: 300px;
      overflow-y: scroll;
      background-color: #333;
    }
    
    #container-inner {
      position: relative;
    }
    
    #item {
      position: absolute;
      left: 50px;
      width: 2px;
      background-color: lightgreen;
      height: 100%;
    }
    <div id="container">
      <div id="container-inner">
        <div id="item"></div>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
      </div>
    </div>

    【讨论】:

    • 有效!与我的其他 hacky 解决方案不同。
    【解决方案2】:

    如果你不想要一个绝对元素,你可以这样做:

    body{
        background-color: #333;
    }
    
    #container {
      height: 300px;
      overflow-y: scroll;
      background-color: #333;
      position: relative;
      border-left:2px solid lightgreen;
      margin-left : 50px;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-03
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2021-01-02
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多