两列伸缩框布局 [英] Two columns flex-box layout

查看:53
本文介绍了两列伸缩框布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建布局,该布局将在两列中包含项目列表。就像我在下面显示的那样:

I need create layout which will contain list of items in two columns. Like i showed below:

.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>


这样的布局问题。如果只有1个项目-它将采用全宽。而且即使有一些项目,我也需要保留列。

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.

推荐答案

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

You can set a max-width for the item, equal to 50%. This will keep it, almost, the same width no matter what. I say almost because you also have borders set.

为了保持宽度完全相同,还必须设置box-sizing:项目的border-box。

In order to keep the width exactly the same, you also have to set box-sizing: border-box for item.

因此,您的代码将为:

.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>

这篇关于两列伸缩框布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆