我有一个简单的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列时出现此问题。
答案 0 :(得分:3)
删除flex增长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>
答案 1 :(得分:0)
设置flex: 1 0 21%
本质上就是设置
flex-grow: 1;
flex-shrink: 0;
flex-basis: 21%;
通过这种方式,21%
部分实际上是无用的,因为您已将其设置为在行的一部分(flex-grow: 1
)内可扩展。要解决此问题,您只需要将flex-basis
设置为任何百分比,而无需设置其他百分比。通过直接定义flex-basis: 21%
来实现。
答案 2 :(得分:0)
我也有一种设置宽度的方法,我不知道这是否是您想要的。
.container {
display:flex;
flex-wrap:wrap;
justify-content:space-between;
}
.item {
background:teal;
margin:10px;
width: 21%;
}
<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>