Keep the middle item centered when side items have different widths

后端 未结 7 1121
长情又很酷
长情又很酷 2020-11-22 17:09

Imagine the following layout, where the dots represent the space between the boxes:

[Left box]......[Center box]......[Right box]

7条回答
  •  有刺的猬
    2020-11-22 17:43

    Instead of defaulting to using flexbox, using grid solves it in 2 lines of CSS without additional markup inside the top level children.

    HTML:

    variable content
    variable content
    variable content which happens to be very long

    CSS:

    .header {
      display: grid;
      grid-template-columns: [first] 20% auto [last] 20%;
    }
    .middle {
      /* use either */
      margin: 0 auto;
      /* or */
      text-align: center;
    }
    

    Flexbox rocks but shouldn't be the answer for everything. In this case grid is clearly the cleanest option.

    Even made a codepen for your testing pleasure: https://codepen.io/anon/pen/mooQOV

提交回复
热议问题