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

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

当前回答

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

其他回答

我们可以使用下一个CSS的类,允许中心垂直和垂直对其父母的任何元素:

.centerElement{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

您可以使用 CSS Flexbox。

#inner {
    display: flex;
    justify-content: center;
}

您可以在此链接中了解更多信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

使用:

<div id="parent">
  <div class="child"></div>
</div>

风格:

#parent {
   display: flex;
   justify-content: center;
}

如果你想把它集中在水平上,你应该写下如下:

#parent {
   display: flex;
   justify-content: center;
   align-items: center;
}

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

<!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" style="width:100%">  
  <div id="inner" style="text-align:center">Foo foo</div>
</div>