【问题标题】:Fixed div related to another div修复了与另一个 div 相关的 div
【发布时间】:2016-06-01 02:10:32
【问题描述】:

我想创建一个固定元素,它在向下和向上滚动时将位于同一位置,但在调整窗口大小时也将在 x 轴上相对于不同的 div。

#blackbox {
  width: 500px;
  height: 2000px;
  background-color: black;
  color: white;
  margin: 0 auto;
}

#floater {
  width: 150px;
  background-color: blue;
  color: white;
  position: fixed;
  top: 50px;
  right: 120px;
  /* want here 10px on right from black box */
}
<html>
  <div id="blackbox">
    This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br> This is blackbox
    <br>
  </div>
  <div id="floater">
    Always 10px from black box
  </div>

</html>

分辨率与我相同时的完美场景:

当屏幕分辨率较小时:

屏幕分辨率更大:

编辑: 我找到了解决方案here

#floater {
    left: calc(50% + 510px); /* 50% + blackbox width + wanted 10px space *.
}

【问题讨论】:

  • 你能告诉我们什么对你有用吗?

标签: html css


【解决方案1】:

一种方法是使用带有display: table; 的包装器div 和另外两个带有display: table-cell; 的包装器div。

那些“表格单元”将并排放置,然后您可以将任何您想要的内容放入其中。

看看:

#wrapper {
  display: table;
}
#blackbox {
  width: 500px;
  height: 2000px;
  background-color: black;
  color: white;
  margin: 0 auto;
  display: table-cell;
}
#floater-wrapper {
  display: table-cell;
}

#floater {
  width: 150px;
  height: 40px;
  background-color: blue;
  color: white;
  margin-left: 10px;
  margin-top: 50px;
}
<html>
<div id='wrapper'>
  <div id="blackbox">
    This is blackbox
    <br>This is blackbox
    <br>This is blackbox
    <br>This is blackbox
    <br>This is blackbox
    <br>
  </div>
  <div id="floater-wrapper">
    <div id="floater">
      Always 10px from black box
    </div>
  </div>
</div>

</html>

【讨论】:

    【解决方案2】:

    试试这个

    #blackbox {
      width: 500px;
      height: 2000px;
      background-color: black;
      color: white;
      margin: 0 auto;
    }
    
    #floater {
      width: 150px;
      background-color: blue;
      color: white;
      position: fixed;
      top: 50px;
      left: 50%;
      /* want here 10px on right from black box */
    }
    <html>
      <div id="blackbox">
        This is blackbox
        <br> This is blackbox
        <br> This is blackbox
        <br> This is blackbox
        <br> This is blackbox
        <br>
      </div>
      <div id="floater">
        Always 10px from black box
      </div>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 2014-12-02
      相关资源
      最近更新 更多