我有一部分的html需要以某种方式显示,但是某些元素可能是可选的,我不确定是否可以使用display:grid
来完成。
我需要有3列,但第一列和最后一列是可选的,当它们不存在时,我需要消除空白。
请注意,标记必须是不带额外包装器的标记:
.grid {
display: grid;
grid-template-columns: auto 1fr auto;
grid-gap: 0 20px;
align-items: center;
background-color: lightgrey;
}
.grid > .image {
grid-column: 1;
grid-row: 1 / span 2;
background-color: red;
}
.grid > .title {
grid-column: 2;
background-color: blue;
}
.grid > .description {
grid-column: 2;
background-color: purple;
}
.grid > .button {
grid-column: 3;
grid-row: 1 / span 2;
background-color: green;
}
<div class="grid">
<div class="image">image</div>
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<p>Unwanted gap when no image :</p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<p>Unwanted gap when no image or button :</p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
</div>
感谢您的帮助
而不是使用网格间隙,而是在各个元素上使用使用边距。
.grid {
display: grid;
grid-auto-columns: auto 1fr auto;
/* grid-gap: 0 20px; */
align-items: center;
background-color: lightgrey;
}
.grid > .image {
margin-right: 20px; /* new */
grid-column: 1;
grid-row: 1 / span 2;
background-color: red;
}
.grid > .button {
margin-left: 20px; /* new */
grid-column: 3;
grid-row: 1 / span 2;
background-color: green;
}
.grid > .title {
grid-column: 2;
background-color: blue;
}
.grid > .description {
grid-column: 2;
background-color: purple;
}
<div class="grid">
<div class="image">image</div>
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<p>Unwanted gap when no image :</p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<p>Unwanted gap when no image or button :</p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
</div>