【问题标题】:Make inner div fixed using only css [duplicate]仅使用 css 修复内部 div [重复]
【发布时间】:2016-09-02 09:17:43
【问题描述】:

我正在尝试使内部 div 相对于它的父 div 固定。我在jsfiddle 上做了一个我的代码示例。问题是当你滚动 div 时。它不再在它的位置上。我的 html 看起来像:

 <div class="outer">
   <div class="inner1">
     Lorem ipsum dolor
   </div>
   <div class="inner2">

   </div>

</div>

和css

    .outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}

.inner1{
  position: absolute;
  width:50px;
  height: auto;
  border: 1px solid blue;
  top: 10px;
  right: 10px;
}
.inner2{
  width: 500px;
  height: 500px;
}

有没有办法让inner1 相对于outer 仅使用css 固定?

【问题讨论】:

  • “CSS 规范要求position:fixed 锚定到viewport,而不是包含定位元素。” 参考this 答案..
  • fixed 与父级无关!它总是停留在给定的位置!
  • 我知道不是!我只想让 inner1 即使在你滚动时也保持在它的位置上......我知道其中一个解决方案是在 JS 中计算偏移量并使用 position: fixed.. 但我的问题是,如果你只能使用 css 来做到这一点

标签: javascript html css


【解决方案1】:

试试这个...

 <style>
.outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}

.inner1{
  position: fixed;
  width:50px;
  height: auto;
  border: 1px solid blue;

}
.inner2{
  width: 500px;
  height: 500px;
}
</style>

【讨论】:

    【解决方案2】:

    你可以试试这个:

    .inner1 {
            position: fixed;
            width: 50px;
            height: auto;
            border: 1px solid blue;
            top: 10px;
            right: calc(100% - 400px); // 400px is the outer div's width
        }
    

    【讨论】:

      【解决方案3】:

      这里正在工作JSfiddle

      <div class="container">
      <div class="header">title</div>
      <div class="cont_elements">
          <div class="element">......</div>
          <div class="element">......</div>
          <div class="element">......</div>
      </div>
      

      和 css 将是

      .header {
          position: absolute;
          top:0;
          /* scrolling out of view :-( */
          z-index:2;
          background-color:pink;
      }
      .container {
          position:relative;
          width:200px;
          height:400px;
          background:gold;
      }
      .cont_elements {overflow-y:scroll; height:100%;}
      .element {
          position: relative;
      }
      

      【讨论】:

        【解决方案4】:

        只需更改 .inner1

        .inner1{
            position: fixed;
            width:50px;
            height: auto;
            border: 1px solid blue;
            margin-top: 10px;
            left: 330px;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-10
          • 2015-09-17
          • 2017-09-23
          • 1970-01-01
          • 1970-01-01
          • 2021-06-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多