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

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

当前回答

HTML:

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

CSS:

#outer{
  width: 500px;
  background-color: #000;
  height: 500px
}
#inner{
  background-color: #333;
  margin: 0 auto;
  width: 50%;
  height: 250px;
}

菲德尔

其他回答

Flex 有超过97%的浏览器支持覆盖范围,可能是解决这些问题的最佳方式:

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

Flexbox 中心 垂直和垂直 中心 调整一个元素

.wrapper {边界: 1px 固体 #678596; 最大宽度: 350px; 边界: 30px 自动;}.parentClass { 显示: flex; 定义内容:中心; 平衡元素:中心; 高度: 300px;}.parentClass div { 边界: 5px; 背景: #678596; 宽度: 50px; 线高度: 50px; 文本平衡:中心; 字体大小: 30px; 颜色: #fff;} <h1>Flexbox 中心 垂直和垂直 中心 平衡元素</h1> <h2>j

如果你不想在内部DIV上设置固定宽度,你可以做这样的事情:

#outer { 宽度: 100%; 文本顺序:中心; } #inner { 显示: inline-block; } <div id="outer"> <div id="inner"> Foo foo</div> </div>

这使得内部的DIV变成一个可以与文本平行集中的内线元素。

如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。

你可以使用:

#element {
    display: table;
    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>