我如何用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 { 边界: 1px dotted 灰色; } #outer { 显示: 网; 地点标题: 中心; 高度: 50px; /* 不需要 */ } <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div> Foo foo</div> </div> </body> </html>
最好的方法是使用桌面细胞显示器(内部),即与显示表(外部)的Div之后,并为内部Div(与桌面细胞显示器)设置垂直调整,并在Div或页面中心的内部Div中使用的每个标签。
注意:您必须将指定的高度设置到外面
它是最好的方式你知道没有位置相对或绝对,你可以使用它在每个浏览器一样。
#outer{ 显示: 表; 高度: 100vh; 宽度: 100%; } #inner{ 显示: 表细胞; 垂直平衡: 中间; 文本平衡: 中心; } <div id="outer"> <div id="inner"> <h1> 设置内容中心 </h1> <div> hi 这是最适合您的项目中心 </div> </div> </div> </div>
首先:你需要给第二 Div 一个宽度:
例如:
HTML
<div id="outter">
<div id="inner"Centered content">
</div
</div>
CSS:
#inner{
width: 50%;
margin: auto;
}
请注意,如果你不给它一个宽度,它将采取整个线的宽度。
如果你不想在内部DIV上设置固定宽度,你可以做这样的事情:
#outer { 宽度: 100%; 文本顺序:中心; } #inner { 显示: inline-block; } <div id="outer"> <div id="inner"> Foo foo</div> </div>
这使得内部的DIV变成一个可以与文本平行集中的内线元素。
#centered { 位置: 绝对; 左: 50%; 边缘左: -100px; } <div id="outer" style="width:200px"> <div id="centered"> Foo foo</div> </div>
确保母元素定位,即相对、固定、绝对或粘贴。
如果你不知道你的 div 的宽度,你可以使用 transform:translateX(-50%);而不是负面边界。
使用 CSS calc(),代码可以变得更简单:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
原则仍然是相同的;把项目放在中间,并补偿宽度。