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

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

当前回答

这对我工作:

#inner {
    position: absolute;
    margin: 0 auto;
    left: 0;
    width: 7%;
    right: 0;
}

在此代码中,您将确定元素的宽度。

其他回答

我使用Flexbox或CSS网络

Flexbox #outer{ 显示: flex;正当内容:中心; } CSS 网络 #outer { 显示: 内线网络; 网络模板线: 100px 100px; 网络模板列: 100px 100px; 网络错误: 3px; }

你可以以多种方式解决这个问题。

最简单的方式之一......

<!DOCTYPE html>
<html>
    <head>
        <style>
            #outer-div {
                width: 100%;
                text-align: center;
                background-color: #000
            }
            #inner-div {
                display: inline-block;
                margin: 0 auto;
                padding: 3px;
                background-color: #888
            }
        </style>
    </head>

    <body>
       <div id ="outer-div" width="100%">
           <div id ="inner-div"> I am a easy horizontally centered div.</div>
       <div>
    </body>
</html>

如果你知道它的宽度,让我们说它是1200像素,去:

.container {
    width:1200px;
    margin-left: calc(50% - 600px);
}

因此,基本上它将添加50%的左边边,低于已知宽的一半。

这是一个垂直中心的最佳例子 <div>

<!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div id="inner">Foo foo</div> </div> </body>

你可以以不同的方式做到这一点. 请参见下面的例子:

1. First Method
#outer {
   text-align: center;
   width: 100%;
}
#inner {
   display: inline-block;
}


2. Second method
#outer {
  position: relative;
  overflow: hidden;
}
.centered {
   position: absolute;
   left: 50%;
}