【问题标题】:Center div in viewport with scrolling通过滚动在视口中居中 div
【发布时间】:2017-02-17 01:26:49
【问题描述】:

我正在尝试将页眉和页脚置于视口的中心(如下面的游戏)。内容垂直和水平滚动,但页眉和页脚应保持在视口上的同一位置。我尝试使用以下 CSS:

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

但这会产生一个仅垂直粘滞的页脚。当内容向任何方向移动时,我需要它留在那个位置。

【问题讨论】:

标签: html css sticky


【解决方案1】:

我相信,问题在于您的 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 2013-11-01
      • 1970-01-01
      相关资源
      最近更新 更多