margin-top 仅当弹性项目被包裹时
margin-top only when the flex item is wrapped
我有一个包含两个弹性项目的弹性容器。我想在第二个上设置一个 margin-top,但只有当它被包裹时而不是在第一个 flex 行上。
如果可能,我想避免使用媒体查询。
我认为第一个元素的 margin-bottom 可能是一个解决方案。但是,当元素未被包裹时,它会在底部添加 space,所以同样的问题。
这是我的代码:
.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>
您可以向两个弹性项目添加一些 margin-top
,并向弹性容器添加相同数量的负值 margin-top
。
这样,flex 容器的负边距将抵消第一行的 flex 项目的边距,但不会抵消包裹到其他行的项目的边距。
.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>
如果你的浏览器支持 CSS gap
属性 你可以这样使用它
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
gap: 20px;
}
gap
在 flex-child 项目周围添加一个额外的 space。如果您只想在顶部和底部添加一些额外的 space,请改用 row-gap
。
对于不支持 gap
属性 的浏览器,您可以使用 lobotomized owl
select 或 select 具有相邻项的每个元素就在它之前,这意味着它不会 select 第一个。
.container > * + * {
margin-top: 20px;
}
如果您只想在元素堆叠在一起时使用 * + *
运算符添加此 marign,则应将其包装在 @media
.
中
我有一个包含两个弹性项目的弹性容器。我想在第二个上设置一个 margin-top,但只有当它被包裹时而不是在第一个 flex 行上。
如果可能,我想避免使用媒体查询。
我认为第一个元素的 margin-bottom 可能是一个解决方案。但是,当元素未被包裹时,它会在底部添加 space,所以同样的问题。
这是我的代码:
.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>
您可以向两个弹性项目添加一些 margin-top
,并向弹性容器添加相同数量的负值 margin-top
。
这样,flex 容器的负边距将抵消第一行的 flex 项目的边距,但不会抵消包裹到其他行的项目的边距。
.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>
如果你的浏览器支持 CSS gap
属性 你可以这样使用它
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
gap: 20px;
}
gap
在 flex-child 项目周围添加一个额外的 space。如果您只想在顶部和底部添加一些额外的 space,请改用 row-gap
。
对于不支持 gap
属性 的浏览器,您可以使用 lobotomized owl
select 或 select 具有相邻项的每个元素就在它之前,这意味着它不会 select 第一个。
.container > * + * {
margin-top: 20px;
}
如果您只想在元素堆叠在一起时使用 * + *
运算符添加此 marign,则应将其包装在 @media
.