我如何用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 内容添加到您的 CSS 文件中,它将自动集中内容。
垂直调整到CSS中中心:
#outer {
display: flex;
justify-content: center;
}
垂直 + 垂直到中心在 CSS 中:
#outer {
display: flex;
justify-content: center;
align-items: center;
}
其他回答
使用:
#outerDiv { 宽度: 500px; } #innerDiv { 宽度: 200px; 边缘: 0 auto; } <div id="outerDiv"> <div id="innerDiv"> 内部内容</div> </div>
试试这:
<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;
}
我已经应用了内线风格到内部 div. 使用此一个:
<div id="outer" style="width:100%">
<div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>
我只是建议使用正当内容:中心;当容器显示为 flex. 和文本平行:中心;当它是关于文本元素。
点击下面的代码并根据要求修改。
#content_block { 边界: 1px 固体黑色; padding: 10px; 宽度: 50%; 文本平衡:中心; } #container { 边界: 1px 固体红色; 宽度: 100%; padding: 20px; 显示: flex; justify-content: center; } <div id="container"> <div id="content_block"> Foo foo check</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;
}
请参见这里的例子