margin-top 仅当 flex item 被包裹时

问题描述 投票:0回答:2

我有一个带有两个弹性项目的弹性容器。我想在第二个上设置一个 margin-top,但只有当它被包裹时而不是在第一个 flex line.

如果可能,我想避免使用媒体查询。

我认为第一个元素的 margin-bottom 可能是一个解决方案。然而,当元素没有被包裹时,它会在底部增加空间,所以同样的问题。

这是我的代码:

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.item-big {
  background: blue;
  width: 300px;
}
.item-small {
  background: red;
  margin-top: 30px;
}
<div class="container">
  <div class="item-big">
    FIRST BIG ELEM
  </div>
  <div class="item-small">
    SECOND SMALL ELEM
  </div>
</div>

css margin flexbox
2个回答
260
投票

您可以向两个弹性项目添加一些

margin-top
,并向弹性容器添加相同数量的负
margin-top

这样,弹性容器的负边距将抵消第一行的弹性项目的边距,但不会抵消包裹到其他行的项目的边距。

.container {
  margin-top: -30px;
}
.item-big, .item-small {
  margin-top: 30px;
}

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-top: -30px;
}
.item-big, .item-small {
  margin-top: 30px;
  background: red;
}
.item-big {
  background: blue;
  width: 300px;
}
<div class="container">
   <div class="item-big">
      FIRST BIG ELEM
   </div>
   <div class="item-small">
      SECOND SMALL ELEM
   </div>
</div>

如今,这个 answer 提出的 flex 布局容器中的 css(行-)间隙属性得到全面支持(MDN)。要走的路🙌🏼.


18
投票

如果您的浏览器支持 CSS

gap
属性,您可以像这样使用它

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  gap: 20px;
}

gap
在 flex-child 项目周围添加额外的空间。如果您只想在顶部和底部添加一些额外的空间,请改用
row-gap

对于不支持

gap
属性的浏览器,您可以使用
lobotomized owl
选择器,它选择前面有相邻项目的每个元素,这意味着它不会选择第一个。

.container > * + * {
  margin-top: 20px;
}

如果您只想在元素彼此堆叠时使用

margin
运算符添加此
* + *
,则应将其包裹在
@media
.

第三个解决方案

:not()
:first-child
CSS pseudo-class

.container:not(:first-child) {
  margin-top: 20px;
}
© www.soinside.com 2019 - 2024. All rights reserved.