2016-05-31 73 views
1

我想要创建一个固定的元素,它将在向下滚动时位于同一位置,但在调整窗口大小时,也会在x轴上与另一个div相对。与另一个div相关的固定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 *. 
} 
+0

你能告诉我们你什么工作? –

回答

1

一种方法是使用与display: table;包装股利和另外两个里面有display: table-cell;

这些“表格单元格”将保持并排,然后你可以把任何你想要的东西放在里面。

请看:

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

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>