Keep the middle item centered when side items have different widths

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

    1. Use three flex items in the container
    2. Set flex: 1 to the first and last ones. This makes them grow equally to fill the available space left by the middle one.
    3. Thus, the middle one will tend to be centered.
    4. However, if the first or last item has a wide content, that flex item will also grow due to the new min-width: auto initial value.

      Note Chrome doesn't seem to implement this properly. However, you can set min-width to -webkit-max-content or -webkit-min-content and it will work too.

    5. Only in that case the middle element will be pushed out of the center.

    .outer-wrapper {
      display: flex;
    }
    .item {
      background: lime;
      margin: 5px;
    }
    .left.inner-wrapper, .right.inner-wrapper {
      flex: 1;
      display: flex;
      min-width: -webkit-min-content; /* Workaround to Chrome bug */
    }
    .right.inner-wrapper {
      justify-content: flex-end;
    }
    .animate {
      animation: anim 5s infinite alternate;
    }
    @keyframes anim {
      from { min-width: 0 }
      to { min-width: 100vw; }
    }
    Left
    Center
    Right
    Left
    Center
    Right
    Left
    Center
    Right

提交回复
热议问题