我如何用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>
当前回答
添加文本:中心;到 parent div
#outer {
text-align: center;
}
HTTPS://jsfiddle.net/7qwxx9rs/
或
#outer > div {
margin: auto;
width: 100px;
}
HTTPS://jsfiddle.net/f8su1fLz/
其他回答
您可以使用链接 https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview
.outer{
display: table;
width: 100%;
height: 100%;
}
.inner {
vertical-align: middle;
}
参考 https://v4-alpha.getbootstrap.com/例子/覆盖/
使用 Sass (SCSS合成) 你可以用混合物做到这一点:
与翻译
// Center horizontal mixin
@mixin center-horizontally {
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
}
// Center horizontal class
.center-horizontally {
@include center-horizontally;
}
在HTML标签中:
<div class="center-horizontally">
I'm centered!
</div>
请记住添加位置:相对;到母 HTML 元素。
与Flexbox
使用Flex,你可以这样做:
@mixin center-horizontally {
display: flex;
justify-content: center;
}
// Center horizontal class
.center-horizontally {
@include center-horizontally;
}
在HTML标签中:
<div class="center-horizontally">
<div>I'm centered!</div>
</div>
试试这个CodePen!
这是一个垂直中心的最佳例子 <div>
<!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div id="inner">Foo foo</div> </div> </body>
您可以添加此代码:
#inner { 宽度: 90%; margin: 0 auto; text-align:center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>
我在各个项目中使用的最好是
<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 链接