如何覆盖flexbox justify-content:space-between?

时间:2015-10-28 15:17:00

标签: html css html5 css3 flexbox

是否可以覆盖space-between以使最后一项水平对齐倒数第二项?或者我应该放弃space-between并使用flex-start和自定义边距?

JSfiddle Demo



.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-between;
  width: 300px;
  margin: 30px auto;
  padding: 0;
  box-sizing: border-box;
  position: relative;
}
.item {
  width: 90px;
  height: 90px;
  background-color: #111;
  margin-bottom: 10px;
}
.next-to-last {
  background-color: blue;
}
.last-item {
  background-color: red;
}

<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item next-to-last"></div>
  <div class="item last-item"></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

假元素方法:

您可以为第4个项目添加假元素,以便5和6彼此相邻。

如果您使用visibility: hidden隐藏元素并保留其占用的空间,这将有效。常见的替代方法display: none 将无效,因为该项目未在flexbox对齐中计算。

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-between;
  width: 300px;
  margin: 30px auto;
  padding: 0;
  box-sizing: border-box;
  position: relative;
}
.item {
  width: 90px;
  height: 90px;
  background-color: #111;
  margin-bottom: 10px;
}
.next-to-last {
  background-color: blue;
}
.last-item {
  background-color: red;
}
.invisible {
  visibility: hidden;
}
<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item invisible"></div> <!-- Invisible fake element -->
  <div class="item next-to-last"></div>
  <div class="item last-item"></div>
</div>

自定义保证金方式:

如果您不想创建其他元素,则需要使用自己的flex-start建议和自定义边距。

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  width: 300px;
  margin: 30px auto;
  padding: 0;
  box-sizing: border-box;
  position: relative;
}
.item {
  width: 90px;
  height: 90px;
  background-color: #111;
  margin-bottom: 10px;
  margin-right: 10px;
}
.next-to-last {
  background-color: blue;
  margin-left: 100px;
}
.last-item {
  background-color: red;
}
<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item next-to-last"></div>
  <div class="item last-item"></div>
</div>