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

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

当前回答

试着和周围玩

margin: 0 auto;

如果你也想集中你的文本,试着使用:

text-align: center;

其他回答

可以使用中心标签为方便

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

注意:我分享这个代码,因为谷歌带我到这个 Stack Overflow 解决方案,除了隐藏的元素没有任何宽度,直到它们显示后才可以重新测量/集中。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="inner" style="display:none;"> <form action=""> <table id="innerTable"> <tr><td> 姓名:</td><input type="text"></td> <tr><td> 电子邮件:</td><td><input type="text"></td>

我很抱歉,但这个90年代的婴儿只是为我工作:

<div id="outer">  
  <center>Foo foo</center>
</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>

克里斯·科伊尔(Chris Coyier)在他的博客上写了一篇关于“在未知中集中”的好文章,这是一个多种解决方案的环节,我发表了一个没有发表在这个问题上,它有更多的浏览器支持,而不是Flexbox解决方案,你不使用显示:表;这可能会破坏其他事情。

/* This parent can be any width and height */
.outer {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.outer:before {
  content: '.';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width: 0;
  overflow: hidden;
}

/* The element to be centered, can
   also be of any width and height */
.inner {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}