我如何用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>
当前回答
将 CSS 添加到您的内部 div. 设置边界: 0 自动,并设置其宽度低于 100%,这是外部 div 的宽度。
<div id="outer" style="width:100%">
<div id="inner" style="margin:0 auto;width:50%">Foo foo</div>
</div>
这将带来所需的结果。
其他回答
最熟悉的方式,它是广泛使用和工作在许多浏览器,包括旧的,是使用边界如下:
#parent { 宽度: 100%; 背景颜色: #CCCCCC; } #child { 宽度: 30%; /* 我们需要宽度 */ 边缘: 0 自动; /* 这是魔法 */ 颜色: #FFFFFF; 背景颜色: #000000; 粘贴: 10px; 文本平衡: 中心; } <div id="parent"> <div id="child"> 我是孩子,我是水平中心! 我的爸爸是一个灰色的 div dude!</div> </div>
运行代码以查看它是如何工作的. 此外,有两个重要的事情你不应该忘记在你的CSS,当你试图以这种方式集中: 边缘: 0 自动;. 这使它是 div 中心,如你想要的。
它不能集中,如果你不给它一个宽度,否则,它将采取,默认情况下,整个水平空间。
首先:你需要给第二 Div 一个宽度:
例如:
HTML
<div id="outter">
<div id="inner"Centered content">
</div
</div>
CSS:
#inner{
width: 50%;
margin: auto;
}
请注意,如果你不给它一个宽度,它将采取整个线的宽度。
我最近发现的一件好事,混合了线高度+垂直平行和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;
}
请参见这里的例子
而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:
<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在视图和内容的顶部。