CSS 将 2 个 Div 垂直居中在另一个内部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5661520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Centering 2 Divs inside another vertically
提问by anothershrubery
I have 2 divs that I want to centre vertically inside another div. At the moment I have:
我有 2 个 div,我想在另一个 div 内垂直居中。目前我有:
Now I understand what is going on here, but I want the left div to be vertically aligned within that container and the right div the same. But they are vertically aligning as a pair and not individually. I have tried various things but can't seem to get it work.
现在我明白这里发生了什么,但我希望左侧 div 在该容器内垂直对齐,右侧 div 相同。但是它们是成对垂直对齐的,而不是单独对齐的。我尝试了各种方法,但似乎无法正常工作。
回答by thirtydot
- Remove
float: left
from#left
and#right
. Instead, use
display: inline-block
:#left, #right { display: inline-block; vertical-align: middle; }
- Due to using
display: inline-block
, you have to deal with the whitespace issue. I chose to remove the whitespace in the HTML between</div>
and<div id="right">
. See herefor what happens if you don't do that. Removing the whitespace really is the easiest fix, but there are other ways.
回答by wdm
Flexbox solution to center vertically:
垂直居中的 Flexbox 解决方案:
#container {
display: flex;
align-items: center;
}
OP's original fiddle modified: http://jsfiddle.net/o3pmyb8c/
OP 的原始小提琴修改:http: //jsfiddle.net/o3pmyb8c/
If you would like to also center horizontallyyou can add justify-content: center;
如果您还想水平居中,您可以添加justify-content: center;