2017-02-17 55 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; 
}