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

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

当前回答

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

<!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>

其他回答

只是这样做:

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

CSS

#outer{
  display: grid;
  place-items: center;
}

给内部 div 一些宽度,并添加 margin:0 auto; 在 CSS 属性中。

首先:你需要给第二 Div 一个宽度:

例如:

HTML

<div id="outter">
    <div id="inner"Centered content">
    </div
</div>

CSS:

 #inner{
     width: 50%;
     margin: auto;
}

请注意,如果你不给它一个宽度,它将采取整个线的宽度。

<div id="outer" style="width:100%">  
  <div id="inner" style="text-align:center">Foo foo</div>
</div>

而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:

<div style="top: 50%; left: 50%;
    height: 100px; width: 100px;
    margin-top: -50px; margin-left: -50px;
    background: url('lib/loading.gif') no-repeat center #fff;
    text-align: center;
    position: fixed; z-index: 9002;">Loading...</div>

它将Div放在视图(垂直和水平)的中心,尺寸和调整尺寸,中心背景图像(垂直和水平),中心文本(水平),并保持Div在视图和内容的顶部。