我需要创建布局,其中包含两列中的项目列表.就像我在下面展示的:
.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>
但是这种布局存在问题.如果只有一个项目 – 它将占用全宽.即使有一些项目,我也需要保留列.
解决方法
您可以为项目设置最大宽度,等于50%.无论如何,这将保持几乎相同的宽度.我说几乎是因为你也设置了边框.
为了保持宽度完全相同,您还必须为item设置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>