我如何用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>
当前回答
试着和周围玩
margin: 0 auto;
如果你也想集中你的文本,试着使用:
text-align: center;
其他回答
我只是使用最简单的解决方案,但它在所有浏览器工作:
<!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 id="outer" style="width:100%"> <div id="inner"><button>hello</button></div> </div>
回归2022
这是一个非常古老的问题,所以我只是试图报告今天的情况:
CSS 网络和 flexbox 是您对中心、水平或垂直的最佳选项; margin:auto 方法工作得好,如果内部内容不是一个盒子(内线区块是好的); margin 50% 与 transform:translateX(50%) 是粗糙的力量,但工作得好; 与绝对的位置和 translateX/Y 也适用于水平和垂直的中心,许多对话使用它,扩展高度
这就是2022年的样子,我希望我们永远不会需要更多的网和 flexbox。
<!DOCTYPE html> <html> <head> <title>Center</title> <style>.outer{ 文本平衡:中心; }.inner{ 宽度: 500px; 边界: 0 自动; 背景: 棕色; 颜色: 红色; } </style> </head> <body> <div class="outer"> <div class="inner"> 此 DIV 是中心的</div> </div> </body>
请尝试一下,它将工作没有HTML中心标签。
.outer { 背景颜色: rgb(230,230,255); 宽度: 100%; 高度: 50px; }.inner { 背景颜色: rgb(200,200,255); 宽度: 50%; 高度: 50px; 边界: 0 auto; } <div class="outer"> <div class="inner"> 边界 0 auto </div> </div>