固定div与另一个div相关

时间:2016-05-31 17:42:15

标签: html css

我想创建一个固定元素,它在向下和向上滚动时处于相同位置,但在调整窗口大小时也会在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>

当分辨率与我的相同时的完美场景: when window is big

当屏幕分辨率较小时: when window is small

Whem screem分辨率更大: enter image description here

修改 我找到了解决方案here

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

2 个答案:

答案 0 :(得分:1)

一种方法是使用包含display: table;的包装div,另外两种包含display: table-cell;

那些&#34; table-cells&#34;将并排存在,然后你可以把任何你想要的东西放在里面。

看看:

&#13;
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

#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>

相关问题