将任意数量的行与任意数量的项目设置为所有项目之间的边距的最动态方式是什么?现在唯一对我有用的是将每个项目包装在一个包装器中,将 flex 基础设置为包装器,将边距设置为子项。与此有关的问题是我无法使每一行与该行中最高的内容具有相同的高度。
情况 1:只有边距底部
https://jsfiddle.net/6oaney4e/6/
这很有效,因为内容保持每行最高项目的高度
html
<div class="wrapper">
<div class="item">
text
</div>
<div class="item">
text
<br>
line2
</div>
<div class="item">
text
</div>
<div class="item">
text
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
css
.wrapper{
display: flex;
flex-flow: row wrap;
margin: -10px;
padding: 10px;
background: green;
}
.item{
flex: 0 0 50%;
background: orange;
margin-bottom: 10px;
}
Run Code Online (Sandbox Code Playgroud)
案例 2:四周边距
https://jsfiddle.net/6oaney4e/7/
出于某种原因,这里的行中断了,我猜这是因为该行无法容纳带有额外边距的项目。
html 与案例 1 相同
css
.wrapper{
display: flex;
flex-flow: row wrap;
margin: -10px;
padding: 10px;
background: green;
}
.item{
flex: 0 0 50%;
background: orange;
margin: 10px;
}
Run Code Online (Sandbox Code Playgroud)
案例 3:包装项目并为内部项目添加边距
https://jsfiddle.net/6oaney4e/8/
那行得通,但现在每行上的项目都没有真正意识到彼此,并且不能具有相同的高度。
html
<div class="wrapper">
<div class="item-wrap">
<div class="item">
text
</div>
</div>
<div class="item-wrap">
<div class="item">
text
<br>
line2
</div>
</div>
<div class="item-wrap">
<div class="item">
text
</div>
</div>
<div class="item-wrap">
<div class="item">
text
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
css
.wrapper{
display: flex;
flex-flow: row wrap;
margin: -10px;
padding: 10px;
background: green;
}
.item-wrap{
flex: 0 0 50%;
}
.item{
background: orange;
margin: 10px;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让 HTML 保持在 CASE 1 中(没有 div.item-wrap),让每行上的项目与 CASE 1 中的项目高度相同,并且间距像 CASE 3 一样工作?
理想情况下,您确实希望使用行并使.item-wrapdiv 成为 flex-parents。
.wrapper {
display: flex;
flex-flow: row wrap;
margin: -10px;
padding: 10px;
background: green;
}
.item-wrap {
flex: 0 0 50%;
display: flex;
}
.item {
background: orange;
margin: 10px;
flex: 1;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="item-wrap">
<div class="item">
text
</div>
</div>
<div class="item-wrap">
<div class="item">
text
<br> line2
</div>
</div>
<div class="item-wrap">
<div class="item">
text
<br> line2
<br> line3
</div>
</div>
<div class="item-wrap">
<div class="item">
text
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
但是,如果您必须保留现有结构,则需要使用calc来调整flex-basis. 像这样的东西:
.wrapper {
display: flex;
flex-flow: row wrap;
background: green;
justify-content: space-between;
}
.item {
flex-grow:0;
flex-shrink:0;
flex-basis:calc(50% - 10px); /* separate properties for IE11 upport */
background: orange;
margin: 5px;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="item">
text
</div>
<div class="item">
text
<br> line2
</div>
<div class="item">
text
<br> line2
<br> line3
</div>
<div class="item">
text
</div>
</div>Run Code Online (Sandbox Code Playgroud)