margin-top 仅当 flex 项目被包裹时 [英] margin-top only when the flex item is wrapped

查看:16
本文介绍了margin-top 仅当 flex 项目被包裹时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个弹性项目的弹性容器.我想在第二个上设置一个 margin-top,但只有在它被包裹时而不是在第一条伸缩线上.

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

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

这是我的代码:

.container {显示:弹性;flex-wrap: 包裹;justify-content:空间环绕;}.item-big {背景:蓝色;宽度:300px;}.item-小{背景:红色;边距顶部:30px;}

<div class="item-big">第一个大元素

<div class="item-small">第二个小元素

解决方案

你可以添加一些 margin-top 到两个 flex 项目,以及一个负的 margin-top与 flex 容器的数量相同.

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

.container {边距顶部:-30px;}.item-大,.item-小{边距顶部:30px;}

.container {显示:弹性;flex-wrap: 包裹;justify-content:空间环绕;边距顶部:-30px;}.item-大,.item-小{边距顶部:30px;背景:红色;}.item-big {背景:蓝色;宽度:300px;}

<div class="item-big">第一个大元素

<div class="item-small">第二个小元素

I have a flex container with two flex items. I want to set a margin-top on the second one, but only when it's wrapped and not at the first flex line.

If possible, I want to avoid using media queries.

I thought margin-bottom on the first element could be a solution. However, it adds space at the bottom when the elements are not wrapped, so same problem.

This is my code:

.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>

解决方案

You can add some margin-top to both flex items, and a negative margin-top of the same amount to the flex container.

This way, the negative margin of the flex container will neutralize the margin of the flex items at the first line, but not the margin of the items that wrapped to other lines.

.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>

这篇关于margin-top 仅当 flex 项目被包裹时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆