2016-05-31 42 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>