我如何用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>
当前回答
我使用Flexbox或CSS网络
Flexbox #outer{ 显示: flex;正当内容:中心; } CSS 网络 #outer { 显示: 内线网络; 网络模板线: 100px 100px; 网络模板列: 100px 100px; 网络错误: 3px; }
你可以以多种方式解决这个问题。
其他回答
我只是使用最简单的解决方案,但它在所有浏览器工作:
<!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>
最简单的方式:
#outer { 宽度: 100%; 文本平衡:中心; } #inner { 边缘:自动; 宽度: 200px; } <div id="outer"> <div id="inner">Blabla</div> </div>
添加文本:中心;到 parent div
#outer {
text-align: center;
}
HTTPS://jsfiddle.net/7qwxx9rs/
或
#outer > div {
margin: auto;
width: 100px;
}
HTTPS://jsfiddle.net/f8su1fLz/
我创建了这个例子,以表明如何垂直和水平地调整。
这个代码基本上就是这样:
#outer {
position: relative;
}
和...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
它会留在中心,即使你重新启动屏幕。
我最近找到了一个方法:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
两个元素必须是相同的宽度,以便正常运作。