代码之家  ›  专栏  ›  技术社区  ›  archvist

Flexbox中心溢出列相邻

  •  0
  • archvist  · 技术社区  · 7 年前

    我想创建3列,但如果列数不是3的倍数,我希望溢出/提醒列居中,而不是左对齐。

    我有点让它与其余的2列分开工作,浮动在前3列下面,相对于 div.hold 而不是上面的行。

    例如,如果它是固定的5列;

    .col-md-4
    .col-md-4
    .col-md-4
    .col-md-4 .offset-md-2
    .col-md-4 .offset-md-2
    

    这是我到目前为止的情况。

    https://jsfiddle.net/m16yctyd/5/

    .hold {
      width: 800px;
      margin: 0px auto;
      background: #ccc;
    }
    
    ul {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      list-style: none;
    }
    
    li {
      width: 33.333%;
      text-align: center;
      display: inline-block;
      vertical-align: middle;
      margin: 30px auto;
    }
    
    li:nth-child(1) {
      background: red;
    }
    
    li:nth-child(2) {
      background: yellow;
    }
    
    li:nth-child(3) {
      background: green;
    }
    
    li:nth-child(4) {
      background: blue;
    }
    
    li:nth-child(5) {
      background: orange;
    }
    <div class="hold">
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
      </ul>
    </div>
    1 回复  |  直到 7 年前
        1
  •  2
  •   Nenad Vracar    7 年前

    您可以使用 justify-content: center 但您还需要删除 margin flex项目的左侧和右侧。

    .hold {
      margin: 0px auto;
      background: #ccc;
    }
    ul {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      list-style: none;
      padding-left: 0;
    }
    li {
      flex: 0 0 33%;
      text-align: center;
      margin: 30px 0;
    }
    li:nth-child(1) {background: red}
    li:nth-child(2) {background: yellow}
    li:nth-child(3) {background: green}
    li:nth-child(4) {background: blue}
    li:nth-child(5) {background: orange
    <div class="hold">
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
      </ul>
    </div>