我如何用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>
当前回答
首先:你需要给第二 Div 一个宽度:
例如:
HTML
<div id="outter">
<div id="inner"Centered content">
</div
</div>
CSS:
#inner{
width: 50%;
margin: auto;
}
请注意,如果你不给它一个宽度,它将采取整个线的宽度。
其他回答
如果你知道它的宽度,让我们说它是1200像素,去:
.container {
width:1200px;
margin-left: calc(50% - 600px);
}
因此,基本上它将添加50%的左边边,低于已知宽的一半。
它也可以用绝对定位来垂直和垂直集中,如下:
#outer{
position: relative;
}
#inner{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%)
}
我只是使用最简单的解决方案,但它在所有浏览器工作:
<!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>
CSS
#inner {
display: table;
margin: 0 auto;
}
HTML
<div id="outer" style="width:100%">
<div id="inner">Foo foo</div>
</div>
我创建了这个例子,以表明如何垂直和水平地调整。
这个代码基本上就是这样:
#outer {
position: relative;
}
和...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
它会留在中心,即使你重新启动屏幕。