我如何用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>
<style>
#outer-div {
width: 100%;
text-align: center;
background-color: #000
}
#inner-div {
display: inline-block;
margin: 0 auto;
padding: 3px;
background-color: #888
}
</style>
</head>
<body>
<div id ="outer-div" width="100%">
<div id ="inner-div"> I am a easy horizontally centered div.</div>
<div>
</body>
</html>
其他回答
使用:
<style>
#outer{
text-align: center;
width: 100%;
}
#inner{
text-align: center;
}
</style>
要在中间调整一个 div 中间的 div -
.outer{ 宽度: 300px; /* 例如 */ 高度: 300px; /* 例如 */ 背景: 红色; }.inner{ 位置: 相对; 顶部: 50%; 左: 50%; 转换: 翻译(-50%, -50%); 宽度: 200px; 高度: 200px; 背景: 黄色; } <body> <div class='outer'> <div class='inner'></div> </div> </body>
这将使中间的内部迪夫均匀,垂直和水平。
<!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中心标签。
一个非常简单的和跨浏览器的答案到水平中心是将这个规则应用到母元素:
.parentBox {
display: flex;
justify-content: center
}
我在各个项目中使用的最好是
<div class="outer">
<div class="inner"></div>
</div>
.outer{
width: 500px;
height: 500px;
position: relative;
background: yellow;
}
.inner{
width: 100px;
height: 100px;
background:red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Fiddle 链接