滚动时在视口中居中 div
Center div in viewport with scrolling
我正在尝试使页眉和页脚在视口中居中(如下面的游戏)。内容会垂直和水平滚动,但页眉和页脚应保持在视口中的同一位置。我尝试使用以下 CSS:
.BottomMenu {
background-color: #ADADAD;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
}
但这会产生一个页脚,该页脚仅 垂直 具有粘性。当内容向 任何 方向移动时,我需要它留在那个位置。
我认为问题在于您的 left
和 right
价值观。下面的代码可以解决问题。
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___|____|
这可以通过为 .BottomMenu
class 设置宽度来实现。
我创建了一个非常基本的 JSFiddle,演示了如何使用固定宽度、边距和定位来使 div 居中。
#bottom-menu {
position:fixed;
bottom:0;
left:50%;
width:250px;
margin-left:-125px;
//optional
padding: 10px;
height:50px;
line-height:50px;
}
我正在尝试使页眉和页脚在视口中居中(如下面的游戏)。内容会垂直和水平滚动,但页眉和页脚应保持在视口中的同一位置。我尝试使用以下 CSS:
.BottomMenu {
background-color: #ADADAD;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
}
但这会产生一个页脚,该页脚仅 垂直 具有粘性。当内容向 任何 方向移动时,我需要它留在那个位置。
我认为问题在于您的 left
和 right
价值观。下面的代码可以解决问题。
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___|____|
这可以通过为 .BottomMenu
class 设置宽度来实现。
我创建了一个非常基本的 JSFiddle,演示了如何使用固定宽度、边距和定位来使 div 居中。
#bottom-menu {
position:fixed;
bottom:0;
left:50%;
width:250px;
margin-left:-125px;
//optional
padding: 10px;
height:50px;
line-height:50px;
}