Keep the middle item centered when side items have different widths

后端 未结 7 1223
长情又很酷
长情又很酷 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:52

    If the left and right boxes would be exactly the same size, I get the desired effect. However when one of the two is a different size the centered box is not truly centered anymore. Is there anyone that can help me?

    Here's a method using flexbox to center the middle item, regardless of the width of siblings.

    Key features:

    • pure CSS
    • no absolute positioning
    • no JS/jQuery

    Use nested flex containers and auto margins:

    .container {
      display: flex;
    }
    .box {
      flex: 1;
      display: flex;
      justify-content: center;
    }
    
    .box:first-child > span { margin-right: auto; }
    
    .box:last-child  > span { margin-left: auto;  }
    
    /* non-essential */
    .box {
      align-items: center;
      border: 1px solid #ccc;
      background-color: lightgreen;
      height: 40px;
    }
    p {
      text-align: center;
      margin: 5px 0 0 0;
    }
    short text
    centered text
    loooooooooooooooong text


    true center

    Here's how it works:

    • The top-level div (.container) is a flex container.
    • Each child div (.box) is now a flex item.
    • Each .box item is given flex: 1 in order to distribute container space equally (more details).
    • Now the items are consuming all space in the row and are equal width.
    • Make each item a (nested) flex container and add justify-content: center.
    • Now each span element is a centered flex item.
    • Use flex auto margins to shift the outer spans left and right.

    You could also forgo justify-content and use auto margins exclusively.

    But justify-content can work here because auto margins always have priority.

    8.1. Aligning with auto margins

    Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

提交回复
热议问题