如何在使用flexbox,flex-wrap和last-of-type的同时从最后一个项目中删除右边距 [英] How to remove right-margin from last item in a row while using flexbox, flex-wrap, and last-of-type

查看:62
本文介绍了如何在使用flexbox,flex-wrap和last-of-type的同时从最后一个项目中删除右边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用flexbox时,如果我想为每个元素添加边距,我通常会这样做:

.flexbox-item {
  flex: 1 0 auto;
  margin-right:10px;
}
.flexbox-item:last-of-type {
  margin-right: 0px;
}

如果我不使用flex-wrap,这将起作用,因为它们的最后一项将始终是行中实际的最后一项.

但是,当我使用flex-wrap时,该行的最后一项会根据窗口宽度而变化(并且会自动添加更多行),这意味着有时会删除第一行中的右边距. /p>

有人知道该问题的解决方案吗?

我不认为这是重复的

这是关于保持行在水平方向上相等,而不是在垂直方向上.

无论如何,我的解决方案使用的是负边距,该负边距可以通过深入研究在该线程上找到,但这并不是最受欢迎的解决方案.这是我的解决方案:

似乎此问题的答案是在父级flexbox容器中添加负边距.

.flexbox-container {
  margin-right:-10px;
}
.flexbox-item {
  flex: 1 0 auto;
  margin-right:10px;
}

然后,当您的flexbox项目更改为100%时,只需从项目中删除右边距即可:

@media (max-width: 767px) {
    .flexbox-item {
      margin-right:0px;
    }
    .flexbox-container {
      margin-right: 0px;
    }
}

如果有更好的解决方案,我会全力以赴.

解决方案

我不确定您的用例.但是,为什么不使用justify-content: space-between而不是margin.然后,您无需删除行中最后一个元素的边距. https://jsfiddle.net/n2vqwg79/

When I use flexbox, if I want a margin to add spacing to each element I would usually do this:

.flexbox-item {
  flex: 1 0 auto;
  margin-right:10px;
}
.flexbox-item:last-of-type {
  margin-right: 0px;
}

This works if I don't use flex-wrap because they last item will always be the actual last item on the row.

When I use flex-wrap however, the last item of the row changes depending on the window width (and more rows are added automatically), meaning I'm removing the right margin from the 1st item in a row sometimes.

Anyone know of a solution to this issue?

EDIT: I don't believe this is a duplicate

This is about keeping rows horizontally equal, not vertically.

Anyway, my solution is using negative margins which can found on that thread by digging through it but it's not the most popular solution. Here's my solution:

Seems that the answer to this issue is to add a negative margin to the parent flexbox container.

.flexbox-container {
  margin-right:-10px;
}
.flexbox-item {
  flex: 1 0 auto;
  margin-right:10px;
}

Then when your flexbox items change to 100%, just remove the right margin from the items:

@media (max-width: 767px) {
    .flexbox-item {
      margin-right:0px;
    }
    .flexbox-container {
      margin-right: 0px;
    }
}

If there is a better solution I'm all ears.

解决方案

I'm not entirely sure about your use-case. But why not use justify-content: space-between instead of margin. Then you don't need to remove margin for the last element in the row. https://jsfiddle.net/n2vqwg79/

这篇关于如何在使用flexbox,flex-wrap和last-of-type的同时从最后一个项目中删除右边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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