只有当Flex项目被包装时,才能使用margin-top [英] margin-top only when the flex item is wrapped

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

问题描述

我有一个flex容器和两个flex项目。我想在第二个边上设置一个边距顶部,但是只有当它被包裹起来,而不是在第一个弯曲线时。



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



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



这是我的代码:


$ b $

  .container {display:flex; flex-wrap:wrap; justify-content:space-around;}。item-big {background:blue; width:300px;}。item-small {background:red; {code>< div class =};}}}   

解决方案

您可以将两个 margin-top 添加到两个弹性项目,而负数 margin-top 与flex容器相同。



通过这种方式,flex容器的负边距将抵消第一行flex项的边距,而不是包装到其他行的项目的边距。

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



$ b

.container {display:柔性; 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>

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>

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

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