Centering floating divs within another div

前端 未结 7 2034
自闭症患者
自闭症患者 2020-11-29 14:58

I\'ve searched other questions and, while this problem seems similar to a couple of others, nothing I\'ve seen so far seems to address the issue that I\'m having.

I

相关标签:
7条回答
  • 2020-11-29 16:04

    With Flexbox you can easily horizontally (and vertically) center floated children inside a div.

    So if you have simple markup like so:

    <div class="wpr">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
    </div>
    

    with CSS:

    .wpr
    {
        width: 400px;
        height: 100px;
        background: pink;
        padding: 10px 30px;
    }
    
    .wpr span
    {
        width: 50px;
        height: 50px;
        background: green;
        float: left; /* **children floated left** */
        margin: 0 5px;
    }
    

    (This is the (expected - and undesirable) RESULT)

    Now add the following rules to the wrapper:

    display: flex;
    justify-content: center; /* align horizontal */
    

    and the floated children get aligned center (DEMO)

    Just for fun, to get vertical alignment as well just add:

    align-items: center; /* align vertical */
    

    DEMO

    0 讨论(0)
提交回复
热议问题