纵向和横向居中,浏览器不允许滚动

时间:2013-03-24 08:13:31

标签: css css-position vertical-alignment centering alignment

我正在使用以下css来纵向和横向展示我的内容;问题是,当您最小化浏览器使其小于内容div时,它会继续居中但无法滚动。内容只是在顶部切断。

#splash-centre-container{
  position: absolute;
  top: 50%;
  left: 50%;
  height: 550px;
  width: 760px;
  min-height: 550px;
  padding: 20px;
  margin: -310px 0 0 -400px;
}

3 个答案:

答案 0 :(得分:4)

这是因为当您将某个内容定位为absolute时,您将其从页面流中拉出来时,它不会“占用空间”。

您希望将min-widthmin-height应用于body(或其容器),以便当屏幕太小时,启动画面居中的元素将永远无法获取小于闪屏,因此不会离开屏幕。

jsFiddle

enter image description here

<强> HTML

<div class="spacer">
    <div id="splash-centre-container">abc</div>
</div>

<强> CSS

html, body { 
    min-width:760px;
    height:100%;
    min-height:550px;
    position:relative;
}
#splash-centre-container {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 550px;
    width: 760px;
    margin: -275px 0 0 -380px;
    background-color:red;
}

答案 1 :(得分:2)

你可以这样做

#splash-centre-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 50%;
  height: 50%;
  position: absolute;
  overflow: auto;
  border: solid black 2px;
}

http://jsfiddle.net/btevfik/XMNTM/

答案 2 :(得分:0)

Chris Coyier发布了我能找到的最佳解决方案here in 2009。我认为它是最好的,因为它垂直和水平地集中内容,它允许动态高度(这里发布的其他答案取决于固定高度,这是不必要的限制)加上滚动较小的屏幕。这对于创建替代模态弹出窗口的居中内联表单非常有用。

我清理并将该代码转换为Sass mixin,以便您可以轻松自定义表单宽度(提示:将表单元素CSS和相关变量添加到Sass mixin中,因为表单元素宽度将限制在居中的内联形式中)

jsFiddle

<强> SCSS

html,
body,
form {
  height: 100%;
  margin: 0;
  padding: 0;
}

@mixin CenteredInlineForm( $ContainerSetName, $formWidth) {
  div.#{$ContainerSetName}_CenteredForm {
    display: table;
    overflow: hidden;
    margin: 0 auto;
    height: 100%;
    width: #{($formWidth + 15)}px;
    div.#{$ContainerSetName}_CenteredFormContentContainer {
      display: table-cell;
      vertical-align: middle;
      div.#{$ContainerSetName}_CenteredFormContent {
        background-color: lightgrey;
        border: 3px solid darkgrey;
        border-radius: 15px;
        padding: 15px;
      }
    }
  }
  *:first-child + html div.#{$ContainerSetName}_CenteredForm {
    position: relative;
  }
  /*ie6 Support: */
  /* * html div.#{$ContainerSetName}_CenteredForm{position:relative;} */
  *:first-child + html div.#{$ContainerSetName}_CenteredFormContentContainer {
    position: absolute;
    top: 50%;
  }
  /*ie6 Only: */
  /* * html div.#{$ContainerSetName}_CenteredFormContentContainer{position:absolute;top:50%;} */
  *:first-child + html div.#{$ContainerSetName}_CenteredFormContent {
    position: relative;
    top: -50%;
  }
}

@include CenteredInlineForm(UserInfoInput, 400);

<强> HTML

<div class="UserInfoInput_CenteredForm">
  <div class="UserInfoInput_CenteredFormContentContainer">
    <div class="UserInfoInput_CenteredFormContent">
      <p>
        Content or form labels/inputs
      </p>
      ...
    </div>
  </div>
</div>