我如何用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>
当前回答
我只是使用最简单的解决方案,但它在所有浏览器工作:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>center a div within a div?</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#outer{
width: 80%;
height: 500px;
background-color: #003;
margin: 0 auto;
}
#outer p{
color: #FFF;
text-align: center;
}
#inner{
background-color: #901;
width: 50%;
height: 100px;
margin: 0 auto;
}
#inner p{
color: #FFF;
text-align: center;
}
</style>
</head>
<body>
<div id="outer"><p>this is the outer div</p>
<div id="inner">
<p>this is the inner div</p>
</div>
</div>
</body>
</html>
其他回答
最簡單的方式之一是使用顯示器: flex. 外部 div 只需要顯示器 flex, 內部需要範圍: 0 auto 以使其以水平為中心。
要垂直集中,只需在另一个Div中集中一个Div,请查看下面的.inter 类评论。
.wrapper { 显示: flex; /* 添加我们想要的任何高度和宽度 */ 高度: 300px; 宽度: 300px; /* 只是这样你可以看到它是中心 */ 背景: peachpuff; }.inner { /* 中心 水平 */ 边界: 0 自动; /* 中心 垂直 * /* 边界: 0 自动; * /* 中心 * / * 边界: 0 自动; * / } <div class="wrapper"> <div class="inner"> 我是 ho
我很抱歉,但这个90年代的婴儿只是为我工作:
<div id="outer">
<center>Foo foo</center>
</div>
我要为这个罪而去地狱吗?
我通常的方式是使用绝对的位置:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
外部迪夫不需要任何额外的属性来工作。
这个方法也很好地工作:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
对于内部<div>,唯一的条件是其高度和宽度不应大于其容器的高度。
#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;
}
它将使内部元素的中心垂直,它工作而不设置特定的宽度。
工作例子在这里: