使用flexbox将两个不均匀的盒子对齐两个

时间:2018-01-25 15:09:51

标签: javascript html css flexbox

我正在创建一个盒子列表。 无论视图的宽度如何,我都希望将它们两两对。 这些方框将分开如下:

 ## For a view of 100 pixel width
 [ 10px <-> [box of 30px] <-> 10px <-> [box of 30px] <-> 10px ]

当盒子数不均匀时,我想在左边对齐最后一项。

这是一个反应原生的项目,因此CSS flex属性是有限的

这是我现在的小提琴:https://jsfiddle.net/hf492cah/

感谢您的时间

2 个答案:

答案 0 :(得分:1)

您可以使用calc() css根据视图计算它们之间的宽度和间距

<强> Updated Fiddle

Stack Snippet

&#13;
&#13;
.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  border: 1px solid silver;
  display: flex;
}

.wrap {
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

.wrap li {
  background: gold;
}

.flex-item {
  background: tomato;
  padding: 5px;
  flex: 0 0 calc(50% - 20px);
  height: 100px;
  margin: calc(40px / 3) 0 0 calc(40px / 3);
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
  box-sizing: border-box;
}
&#13;
<ul class="flex-container wrap">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
  <li class="flex-item">7</li>
  <li class="flex-item">8</li>
  <li class="flex-item">9</li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用justify-content: flex-start;justify-content: space-between;将非完整行对齐到左侧。为了保证框可以跨越整行,您可以设置flex-basis: 33%;

&#13;
&#13;
.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  border: 1px solid silver;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  justify-content: flex-start;
}

.wrap    { 
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}  
.wrap li {
  background: gold;
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 100px;
  height: 100px;
  margin: 10px;
  
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
&#13;
<ul class="flex-container wrap">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
  <li class="flex-item">7</li>
  <li class="flex-item">8</li>
</ul>
&#13;
&#13;
&#13;