我如何用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>
其他回答
我在各个项目中使用的最好是
<div class="outer">
<div class="inner"></div>
</div>
.outer{
width: 500px;
height: 500px;
position: relative;
background: yellow;
}
.inner{
width: 100px;
height: 100px;
background:red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Fiddle 链接
与网
一个非常简单和现代的方式是使用显示器:网:
div { 边界: 1px dotted 灰色; } #outer { 显示: 网; 地点标题: 中心; 高度: 50px; /* 不需要 */ } <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div> Foo foo</div> </div> </body> </html>
.outer { 背景颜色: rgb(230,230,255); 宽度: 100%; 高度: 50px; }.inner { 背景颜色: rgb(200,200,255); 宽度: 50%; 高度: 50px; 边界: 0 auto; } <div class="outer"> <div class="inner"> 边界 0 auto </div> </div>
您可以使用显示器: flex 为您的外部 div 和到水平中心 您必须添加 justify 内容: 中心
#outer{
display: flex;
justify-content: center;
}
或者您可以参观w3schools - CSS flex Property 更多想法。
这肯定会把你的内部都集中在水平上和垂直上,这也适用于所有浏览器,我只是添加了额外的风格,只是为了显示它是如何集中的。
#outer {背景:黑色;位置:相对;宽:150px;高度:150px; } 内部 {背景:白色;位置:绝对;左:50%;顶部:50%;转换:翻译(50%,-50%); -webkit-转换:翻译(50%,-50%); -moz-转换:翻译(50%,-50%); -o-转换:翻译(50%,-50%); } <div id="outer"> <div id="inner">Foo foo</div> </div>
但是,當然,如果你只想它垂直調整,這可能會幫助你。