我如何用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 定义内容属性
它将Flexbox元件调整到容器的中心:
#outer {
display: flex;
justify-content: center;
}
其他回答
这肯定会把你的内部都集中在水平上和垂直上,这也适用于所有浏览器,我只是添加了额外的风格,只是为了显示它是如何集中的。
#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>
但是,當然,如果你只想它垂直調整,這可能會幫助你。
您可以使用 CSS Flexbox。
#inner {
display: flex;
justify-content: center;
}
您可以在此链接中了解更多信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
此分類上一篇: Margin:0px auto:
此分類上一篇: <div id="outer" style="width:100%"> <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>
#inner {
width: 50%;
margin: 0 auto;
}