Html 父 div 内的中心子 div

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

Center child divs inside parent div

htmlcss

提问by flying227

I have a parent div that must stay at 100% with 3 child divs inside. I need to center the 3 child divs, but don't know how.

我有一个父 div,它必须保持 100%,里面有 3 个子 div。我需要将 3 个子 div 居中,但不知道如何。

.parent
{
    width: 100%;    
    border: 1px solid blue;
}

.child
{
    float: left;    
    border: 1px solid red;
    margin: 2px;
}

<div class="parent">
    <div class="child">child1</div>
    <div class="child">child2 - center us child divs! :)</div>
    <div class="child">child3</div>
    <div style="clear: both"></div>
</div>

Here is some example code:

下面是一些示例代码:

http://jsfiddle.net/qdHH3/2/

http://jsfiddle.net/qdHH3/2/

Thanks!

谢谢!

回答by Christian

Try using display: inline-blockand text-align: center

尝试使用display: inline-blocktext-align: center

.parent {
    width: 100%;
    border: 1px solid blue;
    text-align: center;
}

.child {
    display: inline-block;  
    border: 1px solid red;
    margin: 2px;
}

jsFiddle: http://jsfiddle.net/qdHH3/3/

jsFiddle:http: //jsfiddle.net/qdHH3/3/

回答by Roko C. Buljan

Flexsolution: set justify-content: center;to the parentelement:

柔性溶液:设置justify-content: center;元素:

.parent {
  display: flex;
  justify-content: center;
}

.parent, .child { border: 1px solid #000; }
<div class="parent">
    <div class="child">child1</div>
    <div class="child">child2 - center us child divs! :)</div>
    <div class="child">child3</div>
</div>