2017-02-17 33 views
1

我試圖將視圖中的頁眉和頁腳居中(如下面的遊戲一樣)。內容可以垂直和水平滾動,但頁眉和頁腳應該保持在視口上的相同位置。我用下面的CSS嘗試:使用滾動的視口中的中心div

.BottomMenu { 
    background-color: #ADADAD; 
    position: fixed; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    height: 50px; 
} 

但是,這會產生一個頁腳,只有垂直已被置頂。我需要它保持在該點,而內容在任何方向移動。

Example 1

+0

你能鏈接一個JSFiddle嗎? –

+1

此外,我敢肯定這個問題是http://stackoverflow.com/questions/3303173/position-element-fixed-vertically-absolute-horizo​​ntally –

回答

2

的問題,我相信,是你leftright值。下面的代碼將做到這一點。

body { 
 
    width: 5000px; 
 
    height: 5000px; 
 
} 
 

 
#element { 
 
    width: 75px; 
 
    height: 25px; 
 
    position: fixed; 
 
    top: 100%; 
 
    left: 50%; 
 
    transform: translate(-50%, -100%); 
 
    border: solid orange 2px; 
 
}
<div id="element"></div>

translate方法調整元件相對於自身的位置。例如,如果您有一個帶有width: 100px並且設置爲transform: translateX(-50%)的元素,它會將元素50px移動到位置所在的左側。

top: 100%; 
left: 50%; 

作品是這樣的...

_________________ 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|_________________| 
     |___e___| 

transform: translate(-50%, -100%) 

作品是這樣的...

_________________ 
|     | 
|     | 
|     | 
|     | 
|     | 
|     | 
|  _______  | 
|____|___e___|____| 
2

這可以通過使用一組寬度來實現爲.BottomMenu類。

我創建了一個非常基本的JSFiddle,它演示瞭如何使用固定寬度,邊距和定位來保持div居中。

#bottom-menu { 
    position:fixed; 
    bottom:0; 
    left:50%; 
    width:250px; 
    margin-left:-125px; 
    //optional 
    padding: 10px; 
    height:50px; 
    line-height:50px; 
}