两列弹性盒子布局

25

我需要创建一个布局,其中包含两列的项目列表。就像下面展示的那样:

.container {
  border: 1px solid red;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.item {
  border: 1px dashed blue;
  height: 50px;
}
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
</div>

But there is a problem with such layout. If there will be only 1 item - it will take full width. And i need to keep columns even if there are a few items.


2
在子元素中使用flex-basis: 50%。在父元素上使用flex-direction: row;和flex-wrap: wrap;。 此外,以下是一个非常有用的入门指南:https://css-tricks.com/snippets/css/a-guide-to-flexbox/ - Silom
3个回答

37

你可以为该项设置一个最大宽度,等于50%。这将使其保持几乎相同的宽度,无论如何。我说几乎是因为你还设置了边框。

为了保持宽度完全相同,你还需要为该项设置box-sizing: border-box。

所以,你的代码将是:

.item {
  border: 1px dashed blue;
  height: 50px;
  box-sizing: border-box;
  max-width: 50%;
}

.container {
  border: 1px solid red;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.item {
  border: 1px dashed blue;
  height: 50px;
  box-sizing: border-box;
  max-width: 50%;
}
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
</div>


我们如何将其限制为仅两列,以便它不会水平扩展?就像这样 https://share.getcloudapp.com/jkuPArlo - leonardeveloper
1
谷歌告诉我这个答案已经存在1641天了。虽然我并没有要求这种特定的信息,但我还是很喜欢它。这个答案刚刚拯救了我在2021年网站开发课程中的成绩。 - Jolenealaska

5
我更喜欢使用下面的代码:
.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex-basis: 50%;
  box-sizing: border-box;
}

0
如果您想创建“固定两列”而不更改依赖关系(如设备响应),则无需使用Flex。尝试在子元素上使用此方法。
.childs {
display: inline-block;
max-width:50%;
width: 100%;
}


这种方法的主要缺点是:第二列的文本会溢出到第一列。 - cl0ne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接