【问题标题】:How to center a div with a specific width and fixed positioning?如何使具有特定宽度和固定位置的 div 居中?
【发布时间】:2014-03-15 02:04:45
【问题描述】:

我正在编码,并试图将我的 div 水平居中于页面中间。它只是一个普通的 div,现在里面什么都没有。我的代码是这样的:

#wrapper{
width:500px;
height:100%;
position:fixed;
background-color:#fff;
}

基本上,我只想要一个 500px 宽度的白色矩形,水平居中在页面中,占据页面高度的 100%。

谢谢。

【问题讨论】:

    标签: css html alignment css-position center


    【解决方案1】:

    您可以分配left:50%margin-left (width-of-div / 2) 之后,这样您就可以将div 居中在固定/绝对位置

    试试这个:

    #wrapper{
       width:500px;
       height:100%;
       position:fixed;
       background-color:#fff;
       left:50%;
       margin-left:-250px;
    }
    

    DEMO

    【讨论】:

      【解决方案2】:

      您需要使用左 50% 并添加负一半宽度的边距

      #wrapper{
      width:500px;
      height:100%;
      left: 50%;
      margin-left: -250px;
      position:fixed;
      background-color:#fff;
      }
      

      如果您将此 div 用作网页的容器,我建议您取出固定位置并使用 margin: 0 auto; 将 div 居中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-04
        • 2011-03-10
        • 2011-08-31
        • 2017-05-26
        • 2012-04-17
        • 2014-03-20
        • 1970-01-01
        相关资源
        最近更新 更多