CSS 将两个 div 放在包装器中间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5834158/
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:26:04  来源:igfitidea点击:

Center two divs in the middle of a wrapper

css

提问by webmasters

I have this CSS problem:

我有这个 CSS 问题:

<div id="wrap">
    <div id="left">I am div 1</div>
    <div id="right">I am div 2</div>
</div>

I am trying to make "I am div 1 I am div 2"center inside the wrap div. Not sure how to explain it. The design is only in percent, liquid design and I'm stuck.

我正在尝试将“我是 div 1 我是 div 2”放在环绕 div 的中心。不知道怎么解释。设计只是百分比,流动设计,我被卡住了。

Any ideas?

有任何想法吗?

回答by Hymanrugile

If I understand your question correctly, this should work:

如果我正确理解你的问题,这应该有效:

#wrap {
    background: #e7e7e7;
    padding: 5%;
    text-align: center;
    width: 80%;  
}

#left, #right {
     background: #ccc;
     display: inline-block;    
     padding: 2%;   
}

View Example

查看示例

This will center two div blocks within the wrap, side by side.

这将使两个 div 块并排居中。



EDIT: 2015 Flexbox Solution

编辑:2015 Flexbox 解决方案

Flexbox is much more widely supported now and is most likely a better solution for this situation. There are some quirks that come along with the above inline-block method, such as horizontal spacing and vertical alignment issues. Here is the flexbox solution:

Flexbox 现在得到了更广泛的支持,并且很可能是这种情况的更好解决方案。上述 inline-block 方法有一些怪癖,例如水平间距和垂直对齐问题。这是 flexbox 解决方案:

#wrap {
    background: #e7e7e7;
    display: flex;
    justify-content: center;
    padding: 5%; 
    width: 80%;  
}

#left, #right {
    background: #ccc;
    padding: 2%;   
}

View Example

查看示例

Be sure to check Can I Useto confirm that flexbox is supported in the browsers you are supporting.

请务必检查Can I Use以确认您支持的浏览器支持 flexbox。

2019 Edit: Commenter MC9000 brought up that my example is not responsive in percents, as the original question mentioned. I've updated my examples to show that this works with percentage based sizing just like it does with pixel based sizing.

2019 年编辑:评论者 MC9000 提出,我的示例在百分比方面没有响应,正如最初提到的问题。我已经更新了我的示例,以表明这适用于基于百分比的尺寸,就像基于像素的尺寸一样。

回答by kjl

text-align:center;would center this for you:

text-align:center;会以你为中心:

#wrap{
  width:50%;
  border: 1px solid #000;
}

#left, #right{
  text-align: center;
}

Demo: http://jsfiddle.net/DbNs6/1/

演示:http: //jsfiddle.net/DbNs6/1/