我有一个简单的Flexbox布局,如下所示。



.container {
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
}

.item {
  background:teal;
  flex: 1 0 21%; margin:10px;
}

<div class="container">

  <div class="item">
    <h1>Item 1</h1>
    <p>
      This is some test content
    <p>
  </div>

    <div class="item">
    <h1>Item 2</h1>
    <p>
      This is some test content
    <p>
  </div>


  <div class="item">
    <h1>Item 3</h1>
    <p>
      This is some test content
    <p>
  </div>


  <div class="item">
    <h1>Item 4</h1>
    <p>
      This is some test content
    <p>
  </div>


  <div class="item">
    <h1>Item 5</h1>
    <p>
      This is some test content
    <p>
  </div>

</div>





我怎样才能使第5个项目仅占用1/4列?我正在尝试创建4列网格,但是当少于4列时出现此问题。

最佳答案

删除flex grow 1,否则它们将增长以填充行:



.container {
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
}

.item {
  background:teal;
  flex-basis:21%; /* just set the basis and leave grow and shrink as default */
  margin:10px;
}

<div class="container">

  <div class="item">
    <h1>Item 1</h1>
    <p>
      This is some test content
    <p>
  </div>

    <div class="item">
    <h1>Item 2</h1>
    <p>
      This is some test content
    <p>
  </div>


  <div class="item">
    <h1>Item 3</h1>
    <p>
      This is some test content
    <p>
  </div>


  <div class="item">
    <h1>Item 4</h1>
    <p>
      This is some test content
    <p>
  </div>


  <div class="item">
    <h1>Item 5</h1>
    <p>
      This is some test content
    <p>
  </div>

</div>

09-07 18:02