我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
当前回答
专注于水平
演示:
以垂直和垂直为中心
在我的经验中,将盒子垂直和水平中心的最佳方式是使用额外的容器,并应用以下属性:
外部容器:
内部容器:
内容盒子:
.outer 容器 { 显示: 表; 宽度: 100%; 高度: 120px; 背景: #CCC; }. 内部容器 { 显示: 表 细胞; 垂直平面: 中间; 文本平面: 中间; }.centered 内容 { 显示: inline-block; 背景: #FFF; padding: 20px; 边界: 1px 固体 #000; } <div class="outer-container"> <div class="inter-container"> <div class="centered-content">
再看这个Fiddle吧!
其他回答
我找到了类似的路径与边缘左,但它也可以留下。
#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. */
}
我创建了这个例子,以表明如何垂直和水平地调整。
这个代码基本上就是这样:
#outer {
position: relative;
}
和...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
它会留在中心,即使你重新启动屏幕。
给内部 div 一些宽度,并添加 margin:0 auto; 在 CSS 属性中。
#inter { 边界: 0.05em 固体黑色; } #outer { 边界: 0.05em 固体红色; 宽度:100%; 显示: flex; justify-content: center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>
其他解决方案
您可以将此 CSS 应用到内部 <div>:
#inner {
width: 50%;
margin: 0 auto;
}
当然,你不需要设置宽度为50%,任何宽度低于含有<div>的将工作。
如果您正在针对 Internet Explorer 8 (及以后),可能更好地拥有此相反:
#inner {
display: table;
margin: 0 auto;
}
它将使内部元素的中心垂直,它工作而不设置特定的宽度。
工作例子在这里:
要在中间调整一个 div 中间的 div -
.outer{ 宽度: 300px; /* 例如 */ 高度: 300px; /* 例如 */ 背景: 红色; }.inner{ 位置: 相对; 顶部: 50%; 左: 50%; 转换: 翻译(-50%, -50%); 宽度: 200px; 高度: 200px; 背景: 黄色; } <body> <div class='outer'> <div class='inner'></div> </div> </body>
这将使中间的内部迪夫均匀,垂直和水平。