我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

当前回答

使用此代码:

<div id="outer">
    <div id="inner">Foo foo</div>
</div>

#inner {
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

其他回答

中心:自动宽度边界

这个盒子是垂直集中,通过将其右边和左边边界的宽度设置为“自动”。 这是实现垂直集中CSS的最佳方式,并且在大多数使用CSS2支持的浏览器中非常好。 不幸的是,Internet Explorer 5/Windows不响应这种方法 - 该浏览器的缺点,而不是技术。

Internet Explorer 5/Windows 不正确地应用CSS“文本平衡”属性到区块级元素。 声明“文本平衡:中心”为包含区块级元素(通常是BODY元素)的垂直集中在Internet Explorer 5/Windows中的框架。

body {
    margin: 50px 0px;
    padding: 0px;
    text-align: center;
}

#Content {
    width: 500px;
    margin: 0px auto;
    text-align: left;
    padding: 15px;
    border: 1px dashed #333;
    background-color: #EEE;
}

http://bluerobot.com/web/css/center1.html

回归2022

这是一个非常古老的问题,所以我只是试图报告今天的情况:

CSS 网络和 flexbox 是您对中心、水平或垂直的最佳选项; margin:auto 方法工作得好,如果内部内容不是一个盒子(内线区块是好的); margin 50% 与 transform:translateX(50%) 是粗糙的力量,但工作得好; 与绝对的位置和 translateX/Y 也适用于水平和垂直的中心,许多对话使用它,扩展高度

这就是2022年的样子,我希望我们永远不会需要更多的网和 flexbox。

我知道我稍晚回答这个问题,我没有打扰阅读每一个答案,所以这可能是一个重复。

inner { width: 50%; background-color: Khaki; margin: 0 auto; }

我只是使用最简单的解决方案,但它在所有浏览器工作:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>center a div within a div?</title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }

            #outer{
                width: 80%;
                height: 500px;
                background-color: #003;
                margin: 0 auto;
            }

            #outer p{
                color: #FFF;
                text-align: center;
            }

            #inner{
                background-color: #901;
                width: 50%;
                height: 100px;
                margin: 0 auto;

            }

            #inner p{
                color: #FFF;
                text-align: center;
            }
        </style>
    </head>

    <body>
        <div id="outer"><p>this is the outer div</p>
            <div id="inner">
                <p>this is the inner div</p>
            </div>
        </div>
    </body>
</html>

是的,这是一个短暂而干净的水平调整代码。

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}