我想创建一个固定元素,它在向下和向上滚动时处于相同位置,但在调整窗口大小时也会在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 *.
}
答案 0 :(得分:1)
一种方法是使用包含display: table;
的包装div,另外两种包含display: table-cell;
。
那些&#34; table-cells&#34;将并排存在,然后你可以把任何你想要的东西放在里面。
看看:
#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;
答案 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>