Aligning elements left and center with flexbox

前端 未结 7 469
眼角桃花
眼角桃花 2020-11-29 01:12

I\'m using flexbox to align my child elements. What I\'d like to do is center one element and leave the other aligned to the very left. Normally I would just set the left el

7条回答
  •  春和景丽
    2020-11-29 02:10

    Add third empty element:

    Left
    Center

    And the following style:

    .parent {
      display: flex;
    }
    .left, .right {
      flex: 1;
    }
    

    Only left and right are set to grow and thanks to the facts that...

    • there are only two growing elements (doesn't matter if empty) and
    • that both get same widths (they'll evenly distribute the available space)

    ...center element will always be perfectly centered.

    This is much better than accepted answer in my opinion because you do not have to copy left content to right and hide it to get same width for both sides, it just magically happens (flexbox is magical).


    In action:

    .parent {
      display: flex;
    }
    
    .left,
    .right {
      flex: 1;
    }
    
    
    /* Styles for demonstration */
    .parent {
      padding: 5px;
      border: 2px solid #000;
    }
    .left,
    .right {
      padding: 3px;
      border: 2px solid red;
    }
    .center {
      margin: 0 3px;
      padding: 3px;
      border: 2px solid blue;
    }
    Left
    Center

提交回复
热议问题