36

我有一个必须保持 100% 的父 div,里面有 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>

这是一个 JSFIddle:

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

4

3 回答 3

51

尝试使用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/

于 2012-10-26T17:16:35.547 回答
21

Flex解​​决方案:设置justify-content: center;为父元素:

.parent {
  display: flex;
  justify-content: center;
  /* align-items: center; /* To align vertically, if needed */
}

.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>

于 2019-03-02T17:32:07.227 回答
2
.child {

    $box-size: 100%;
    
    width: $box-size;
    height: $box-size;

    display: flex;  
    justify-content: center;
    align-items: center;
}
于 2020-10-06T15:37:48.650 回答