【问题标题】:Centering box into middle of page using CSS使用 CSS 将框居中到页面中间
【发布时间】:2014-01-04 17:48:01
【问题描述】:

我刚开始使用 HTML 和 CSS 制作简单的网页,我想将我的内容放在页面中间。使用我的代码,我的内容从左侧和右侧居中,但我也想从顶部和底部居中。如果您要测试我的代码,您会看到顶部没有间距。我将如何解决这个问题,使其不仅从左到右,而且从顶部和底部都有中心?

我的 CSS 代码如下所示:

body {
width: 100%;
height: 100%;
background-color: green;
}

#homePage {
    width: 960px;
    height: 600px;
    background-color: white;
    margin: 0 auto;
}

我的 html 代码如下所示:

<body>
    <div id="homePage">
        <header> Logo and Twitter </header> 
        <ul id="pageNav">
            <li><a href="index.html">Home</a></li>
            <li><a href="features.html">Features</a></li>
            <li><a href="purchase.html">Purchase</a></li>
            <li><a href="contact.html">Contact</a></li> 
        </ul>               
        <footer> Content for footer goes here </footer>
    </div>                                  
</body>  

【问题讨论】:

标签: html css margin


【解决方案1】:

您为什么不尝试更改显示? 例如:

#homePage {
  width: 960px;
  height: 600px;
  background-color: white;
  margin: auto;
  display:block;
}

【讨论】:

    【解决方案2】:

    j08691 的伟大 CSS 技巧!您也可以在页面加载和调整大小时尝试此操作:

    var _nBodyHeight = $('body').height();
    var _nTop = (_nBodyHeight/2) - ($('#homePage').height()/2);
    $('#homePage').css('top', _nTop);
    

    【讨论】:

      【解决方案3】:

      垂直居中对齐不像使用宽度和边距的水平对齐那样容易。对我来说最好的解决方案是

      How to vertically center a div for all browsers?

      它不包含任何 hack 并且适合响应式设计

      【讨论】:

        【解决方案4】:

        你可以像这样使用定位:

        body {
            background-color: green;
        }
        #homePage {
            width: 960px;
            height: 600px;
            background-color: white;
            margin: auto;
            position:absolute;
            top:0;
            bottom:0;
            left:0;
            right:0;
        }
        

        jsFiddle example

        通过在#homePage 上使用绝对定位,将顶部、右侧、底部和左侧设置为零,并将边距设置为自动,它将水平和垂直居中。

        【讨论】:

          【解决方案5】:

          谷歌“死点 css”。注意拼写。你会得到this invaluable link

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-02-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-07-25
            • 2014-04-04
            • 2019-10-12
            相关资源
            最近更新 更多