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

标签 html css 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>

最佳答案

伪元素方法:

您可以为第 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>


自定义 margin 方法:

如果您不想创建额外的元素,那么您需要使用您自己的建议 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>

关于html - 如何覆盖 flexbox justify-content : space-between?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394866/

相关文章:

javascript - 通过 Javascript 添加多个表行

javascript - 想要显示同一文件夹中其他html页面中一个html页面的图像数量

javascript - 如何在每次鼠标悬停事件时更改单个 div 的颜色?

css - 车身无余量

html - flexbox:边距影响基线?

html - 如何使用 flexbox 水平放置 3 个按钮?

javascript - 使用 jQuery 显示或隐藏 div 元素

html - 标题上的居中对齐按钮(并做出响应)

angular - 为什么我不能直接设置 Angular Material 步进器元素的样式?

javascript - 找到没有属性的 DOM 元素?