【问题标题】:div needs to be centered horizontally and fully occupy vertical spacediv需要水平居中并完全占据垂直空间
【发布时间】:2013-11-20 04:44:15
【问题描述】:

我有类似于以下结构的东西:

<html>
<body>
    <div>
    </div>
</body>
</html>

我希望内部 div 占据页面的整个垂直高度,除了顶部和底部的 8px 边距。我还希望这个 div 在 body 中水平居中,左右两边的最小边距为 8px。我不希望页面滚动并且需要不惜一切代价避免使用 calc() 以获得浏览器支持能力。

我试过了:

html, body{
    height: 100%;
}
div {
    position: absolute;
    top: 8px;
    bottom: 8px;
}

强制它留下一个 8px 的“边距”很好,但是现在如果不使用 calc() 就不可能将它水平居中,因为它的宽度是可变的,并且没有与之相关的元素。

【问题讨论】:

    标签: html css


    【解决方案1】:

    我希望我能正确理解您的问题...您希望 div 填满整个窗口,除了 8px...对吗?

    你可以使用这个 CSS 来做到这一点:

    div {
        background: lightblue;
        position: absolute;
        top: 8px;
        left: 8px;
        bottom: 8px;
        right: 8px;
    }
    

    检查demo

    [选项 2]

    如果您希望 div 具有固定宽度(或使用 max-widthmin-width 半固定),您可以使用以下代码:

    html, body {
        margin: 0;
        padding: 0;
        height: 100%;
    }
    body {
        padding: 8px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;    
    }
    div {
        background: lightblue;
        width: 300px;
        margin: 0 auto;
        height: 100%;
    }
    

    它说 body 是 100% 的高度和宽度,并计算它的宽度内的填充(因此box-sizing)属性。然后你可以指定div的宽度,并使用margin: 0 auto居中。

    检查updated demo

    【讨论】:

      【解决方案2】:
      div{
        display: block;
        margin-left: auto;
        margin-right: auto;
      }
      

      居中的 div

      更新: 删除位置:绝对; FIDDLE

      【讨论】:

      • 这样做的问题是它会完美居中,但它需要占据整个可用的垂直空间(除了上下8px)
      【解决方案3】:

      你可以使用边距:

      div {
         margin: 0 auto;
      }
      

      【讨论】:

        【解决方案4】:

        我觉得最好引入一个新的div:

        <body>
        
        <div class="container">
          <div class="center"></div>
        </div>
        
        </body>
        

        然后在你的 CSS 中你可以这样做:

        .container {
          position: absolute;
          top: 8px;
          bottom: 8px;
          left: 0;
          right: 0;
        }
        .center {
          margin: 0 auto;
        }
        

        【讨论】:

          【解决方案5】:

          http://jsfiddle.net/5X79H/1/

          以下代码将使您的 div 居中:

          <body>
          
          <div class="container">
            <div class="center"></div>
          </div>
          
          </body>
          

          风格:

          .center {
              margin-left: auto;
              margin-right: auto;
              display: inline-block;
              background-color:maroon; 
              width:100px; 
              height: 100px;
          }
          .container{
                 width:100%;
              text-align: center;
          
          }
          

          【讨论】:

            猜你喜欢
            • 2014-11-22
            • 2015-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-09-16
            • 2012-12-16
            • 2013-10-14
            • 1970-01-01
            相关资源
            最近更新 更多