Keep the middle item centered when side items have different widths

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

    Here's an answer that uses grid instead of flexbox. This solution doesn't require extra grandchild elements in the HTML like the accepted answer does. And it works correctly even when the content on one side gets long enough to overflow into the center, unlike the grid answer from 2019.

    The one thing this solution doesn't do is show an ellipsis or hide the extra content in the center box, as described in the question.

    section {
      display: grid;
      grid-template-columns: 1fr auto 1fr;
    }
    
    section > *:last-child {
      white-space: nowrap;
      text-align: right;
    }
    
    /* not essential; just for demo purposes */
    section {
      background-color: #eee;
      font-family: helvetica, arial;
      font-size: 10pt;
      padding: 4px;
    }
    
    section > * {
      border: 1px solid #bbb;
      padding: 2px;
    }
    left
    center
    right side is longer
    left
    center
    right side is much, much longer
    left
    center
    right side is much, much longer, super long in fact

提交回复
热议问题