我有一个CSS
grid
,有时并不是所有的元素都被使用。在实际用例中,我使用 grid
作为输入小部件,其中可能有额外的帮助文本或错误放入特定的 grid-area
中。我遇到的问题是 grid-gap
,如果该行为空,它仍然应用间隙。这会导致底部出现双行间隙。有没有办法禁止显示空行之间的间隙?
我一直面临这个问题,它使得网格间隙对我来说无法使用,所以一般我不使用网格间隙,而是使用更复杂的边距设置。
.parent {
background: gray;
padding: 16px;
margin: 16px;
display: grid;
grid-template-columns: 64px 128px;
grid-template-areas:
"childa childb"
"childc childd"
"childe childf";
grid-gap: 16px;
}
[class^="child"] {
background-color: red;
}
.childa {
grid-area: childa;
}
.childb {
grid-area: childb;
}
.childc {
grid-area: childc;
}
.childd {
grid-area: childd;
}
.childe {
grid-area: childe;
}
.childf {
grid-area: childf;
}
<p>Grid gap is okay if all cells filled:</p>
<div class="parent">
<span class="childa">cell A</span>
<span class="childc">cell C</span>
<span class="childb">cell B</span>
<span class="childe">cell E</span>
<span class="childf">cell F</span>
<span class="childd">cell D</span>
</div>
<p>Note the double gap at the bottom due to the empty row:</p>
<div class="parent">
<span class="childa">cell A</span>
<span class="childb">cell B</span>
<span class="childd">cell D</span>
</div>
不要定义区域,而是定义位置:
.parent {
background: gray;
padding: 16px;
margin: 16px;
display: grid;
grid-gap: 16px;
}
[class^="child"] {
background-color: red;
}
.childa { grid-area: 1/1 } /* row / column */
.childb { grid-area: 1/2 }
.childc { grid-area: 2/1 }
.childd { grid-area: 2/2 }
.childe { grid-area: 3/1 }
.childf { grid-area: 3/2 }
<div class="parent">
<span class="childa">cell A</span>
<span class="childc">cell C</span>
<span class="childb">cell B</span>
<span class="childe">cell E</span>
<span class="childf">cell F</span>
<span class="childd">cell D</span>
</div>
<div class="parent">
<span class="childa">cell A</span>
<span class="childb">cell B</span>
<span class="childd">cell D</span>
</div>
也像下面这样:
.parent {
background: gray;
padding: 16px;
margin: 16px;
display: grid;
grid-auto-flow:dense; /* don't forget this */
grid-gap: 16px;
}
[class^="child"] {
background-color: red;
}
.childa,
.childc,
.childe { grid-column: 1 }
.childb,
.childd,
.childf { grid-column: 2 }
<div class="parent">
<span class="childa">cell A</span>
<span class="childc">cell C</span>
<span class="childb">cell B</span>
<span class="childe">cell E</span>
<span class="childf">cell F</span>
<span class="childd">cell D</span>
</div>
<div class="parent">
<span class="childa">cell A</span>
<span class="childb">cell B</span>
<span class="childd">cell D</span>
</div>
<div class="parent">
<span class="childa">cell A</span>
<span class="childb">cell B</span>
<span class="childf">cell F</span>
</div>