我如何用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 {
position: relative;
}
和...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
它会留在中心,即使你重新启动屏幕。
其他回答
只需将此 CSS 内容添加到您的 CSS 文件中,它将自动集中内容。
垂直调整到CSS中中心:
#outer {
display: flex;
justify-content: center;
}
垂直 + 垂直到中心在 CSS 中:
#outer {
display: flex;
justify-content: center;
align-items: center;
}
#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
它与合理的现代浏览器(Firefox,Safari/WebKit,Chrome,Internet & Explorer & 10,Opera等)工作。
.content { 位置: 绝对; 左: 50%; 顶: 50%; 转换: 翻译(-50%, -50%); } <div class="content"> 这与任何内容工作</div>
在 Codepen 或 JSBin 上加入它。
使用下面的 CSS 内容为 #inner div:
#inner {
width: 50%;
margin-left: 25%;
}
我主要使用这个CSS内容为中心Divs。