我如何用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>
当前回答
我认为这将是一个解决方案:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
两个元素必须是相同的宽度,以便单独运作。
其他回答
你可以以不同的方式做到这一点. 请参见下面的例子:
1. First Method
#outer {
text-align: center;
width: 100%;
}
#inner {
display: inline-block;
}
2. Second method
#outer {
position: relative;
overflow: hidden;
}
.centered {
position: absolute;
left: 50%;
}
要在中间调整一个 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>
<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>
这对我工作:
#inner {
position: absolute;
margin: 0 auto;
left: 0;
width: 7%;
right: 0;
}
在此代码中,您将确定元素的宽度。
如果你有一个父母的某种高度说,身体{高度:200px} 或如下有父母 div#outer 高度200px,然后添加CSS内容如下
HTML:
<div id="outer">
<div id="centered">Foo foo</div>
</div>
CSS:
#outer{
display: flex;
width: 100%;
height: 200px;
}
#centered {
margin: auto;
}
然后,儿童内容,说 div#中心内容,将垂直或垂直中间,不使用任何位置的CSS。
#centered {
margin: 0px auto;
}
或
#outer{
display: flex;
width: 100%;
height: 200px;
}
#centered {
margin: auto;
}
<div id="outer">
<div id="centered">Foo foo</div>
</div>
演示: https://jsfiddle.net/jinny/p3x5jb81/5/
只添加一个界限显示内部 div 不是 100% 默认:
#outer{ 显示: flex; 宽度: 100%; 高度: 200px; 边界: 1px 固体 #000000; } #centered { 边界: auto; 边界: 1px 固体 #000000; } <div id="outer"> <div id="centered"> Foo foo</div> </div>
DEMO: http://jsfiddle.net/jinny/p3x5jb81/9