我如何用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>
当前回答
而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:
<div style="top: 50%; left: 50%;
height: 100px; width: 100px;
margin-top: -50px; margin-left: -50px;
background: url('lib/loading.gif') no-repeat center #fff;
text-align: center;
position: fixed; z-index: 9002;">Loading...</div>
它将Div放在视图(垂直和水平)的中心,尺寸和调整尺寸,中心背景图像(垂直和水平),中心文本(水平),并保持Div在视图和内容的顶部。
其他回答
我最近发现的一件好事,混合了线高度+垂直平行和50%左线技巧的使用,你可以在另一个动态尺寸的盒子内集中一个动态尺寸的盒子,在水平和垂直,使用纯粹的CSS。
请注意,您必须使用在现代浏览器 + Internet Explorer 8 中测试的 spans(和 inline-block)。
<h1>Center dynamic box using only css test</h1>
<div class="container">
<div class="center">
<div class="center-container">
<span class="dyn-box">
<div class="dyn-head">This is a head</div>
<div class="dyn-body">
This is a body<br />
Content<br />
Content<br />
Content<br />
Content<br />
</div>
</span>
</div>
</div>
</div>
CSS:
.container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
overflow: hidden;
}
.center {
position: absolute;
left: 50%;
top: 50%;
}
.center-container {
position: absolute;
left: -2500px;
top: -2500px;
width: 5000px;
height: 5000px;
line-height: 5000px;
text-align: center;
overflow: hidden;
}
.dyn-box {
display: inline-block;
vertical-align: middle;
line-height: 100%;
/* Purely asthetic below this point */
background: #808080;
padding: 13px;
border-radius: 11px;
font-family: arial;
}
.dyn-head {
background: red;
color: white;
min-width: 300px;
padding: 20px;
font-size: 23px;
}
.dyn-body {
padding: 10px;
background: white;
color: red;
}
请参见这里的例子
根据您的情况,最简单的解决方案可能是:
margin: 0 auto; float: none;
#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;
}
它将使内部元素的中心垂直,它工作而不设置特定的宽度。
工作例子在这里:
这就是你想要的最短的方式。
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
它不能集中,如果你不给它一个宽度,否则,它将采取,默认情况下,整个水平空间。