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

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

当前回答

我找到了类似的路径与边缘左,但它也可以留下。

#inner {
    width: 100%;
    max-width: 65px; /* To adapt to screen width. It can be whatever you want. */
    left: 65px; /* This has to be approximately the same as the max-width. */
}

其他回答

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

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



#outer{
     display:flex;
     align-items:center;
}

试试这:

<div id="a">
    <div id="b"></div>
</div>

CSS:

#a{
   border: 1px solid red;
   height: 120px;
   width: 400px
}

#b{
   border: 1px solid blue;
   height: 90px;
   width: 300px;
   position: relative;
   margin-left: auto;
   margin-right: auto;
}

注意:我分享这个代码,因为谷歌带我到这个 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>

最好的方法是使用桌面细胞显示器(内部),即与显示表(外部)的Div之后,并为内部Div(与桌面细胞显示器)设置垂直调整,并在Div或页面中心的内部Div中使用的每个标签。

注意:您必须将指定的高度设置到外面

它是最好的方式你知道没有位置相对或绝对,你可以使用它在每个浏览器一样。

#outer{ 显示: 表; 高度: 100vh; 宽度: 100%; } #inner{ 显示: 表细胞; 垂直平衡: 中间; 文本平衡: 中心; } <div id="outer"> <div id="inner"> <h1> 设置内容中心 </h1> <div> hi 这是最适合您的项目中心 </div> </div> </div> </div>