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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:15:04  来源:igfitidea点击:

Centering 2 Divs inside another vertically

css

提问by anothershrubery

I have 2 divs that I want to centre vertically inside another div. At the moment I have:

我有 2 个 div,我想在另一个 div 内垂直居中。目前我有:

http://jsfiddle.net/5vpA3/1/

http://jsfiddle.net/5vpA3/1/

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

Live Demo

现场演示

  • Remove float: leftfrom #leftand #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.
  • float: left#left和 中删除#right
  • 相反,使用display: inline-block

    #left, #right {
        display: inline-block;
        vertical-align: middle;
    }
    
  • 由于使用display: inline-block,您必须处理空格问题。我选择删除 HTML 中</div>和之间的空格<div id="right">。如果您不这样做,请参阅此处了解会发生什么。删除空格确实是最简单的解决方法,但还有其他方法

回答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;