Change justify-content value when flex items overflow container

前端 未结 1 1926
野的像风
野的像风 2021-02-05 03:50

Look at following fiddle https://jsfiddle.net/27x7rvx6

The CSS (#test is flexbox container, and .items are its children):

#test         


        
相关标签:
1条回答
  • 2021-02-05 04:49

    justify-content is not the right approach to center because of the problem you describe.

    Instead, I recommend auto margins. You can use them to center:

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

    And they behave as you want with overflow:

    Overflowing boxes ignore their auto margins and overflow in the end direction.

    For example, you can set margin-left: auto to the first flex item and margin-right: auto to the last one, or insert ::before and ::after pseudo-elements.

    .test {
      display: flex;
      flex-flow: row nowrap;
      width: 200px;
      border: 2px solid red;
      margin: 10px;
    }
    .wide.test {
      width: 500px;
    }
    .test::before, .test::after {
      content: '';  /* Insert pseudo-element */
      margin: auto; /* Make it push flex items to the center */
    }
    .item {
      flex: 0 0 50px;
      margin-right: 10px;
      background: blue;
      height: 50px;
      border: 2px solid black;
    }
    <div class="test">
      <div class="item"></div><div class="item"></div><div class="item"></div>
      <div class="item"></div><div class="item"></div><div class="item"></div>
    </div>
    <div class="wide test">
      <div class="item"></div><div class="item"></div><div class="item"></div>
      <div class="item"></div><div class="item"></div><div class="item"></div>
    </div>

    0 讨论(0)
提交回复
热议问题