我如何用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>
其他回答
中心的主要属性是边界:自动和宽度:根据要求:
.DivCenter{
width: 50%;
margin: auto;
border: 3px solid #000;
padding: 10px;
}
设置宽度,并设置边缘向左和边缘向右到自动。 这是仅限于水平,但是. 如果你想要两种方式,你只会做这两种方式. 不要害怕尝试; 它不像你会打破任何东西。
CSS
#inner {
display: table;
margin: 0 auto;
}
HTML
<div id="outer" style="width:100%">
<div id="inner">Foo foo</div>
</div>
我已经应用了内线风格到内部 div. 使用此一个:
<div id="outer" style="width:100%">
<div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>
Flex 有超过97%的浏览器支持覆盖范围,可能是解决这些问题的最佳方式:
#outer {
display: flex;
justify-content: center;
}