我看到额外的空间被添加到网格元素,导致元素未对齐但无法弄清楚它来自哪里(边距,元素的填充无效,网格元素对齐以垂直和水平开始)。
编辑:我试图将包装大小限制为 820x410,这确实消除了差距。我知道网格列被拉伸(stretch)以填充包装器 div。虽然这可以解决问题,但我仍然不明白额外的垂直间隙是从哪里来的。
样式:
#wrapper {
display: grid;
grid-template-rows: 2fr;
grid-template-columns: 2fr repeat(2, 1fr);
grid-column-gap: 10px;
grid-row-gap: 10px;
justify-items: start;
align-items: start;
}
#wrapper * {
margin: 0;
padding: 0;
}
figure {
display: block;
vertical-align: bottom;
line-height: 0;
}
figure img {
display: block;
vertical-align: bottom;
line-height: 0;
}
#wrapper {
width: 860px;
}
#wrapper>figure:first-child {
grid-area: 1 / 1 / 3 / 2;
}
布局:
<div id="wrapper">
<figure id="element1">
<img src="http://placehold.it/400x410" />
</figure>
<figure id="element2">
<img src="http://placehold.it/200x200" />
</figure>
<figure id="element3">
<img src="http://placehold.it/200x200" />
</figure>
<figure id="element4">
<img src="http://placehold.it/200x200" />
</figure>
<figure id="element5">
<img src="http://placehold.it/200x200" />
</figure>
</div>
最佳答案
您需要在img
中添加width: 100%
。
为什么?
因为你的包装器是 860px
并且你有 2 列,等分,grid-gap
为 10px
所以每一列都有420px
+ 10px
来自 grid-gap
水平,总共 430px
,但是你的图片只有 400px
宽,因此您的左栏有 20px 的空间,右栏有 10px 的空间,因为它分为 210px
您的解决方案是在 img
中应用 width:100%
以始终填充列和 height:100%
(如果你想像我下面的代码一样使用响应)
#wrapper {
display: grid;
grid-template-rows: 2fr;
grid-template-columns: 2fr repeat(2, 1fr);
grid-gap: 10px
}
#wrapper * {
margin: 0;
padding: 0;
}
figure {
border: 1px dotted red
}
figure img {
display: block;
vertical-align: bottom;
line-height: 0;
width: 100%;
height: 100%
}
#wrapper {
max-width: 860px;
}
#wrapper>figure:first-child {
grid-area: 1 / 1 / 3 / 2;
}
<div id="wrapper">
<figure id="element1">
<img src="http://placehold.it/400x410" />
</figure>
<figure id="element2">
<img src="http://placehold.it/200x200" />
</figure>
<figure id="element3">
<img src="http://placehold.it/200x200" />
</figure>
<figure id="element4">
<img src="http://placehold.it/200x200" />
</figure>
<figure id="element5">
<img src="http://placehold.it/200x200" />
</figure>
</div>
关于html - 在网格布局中添加到图形元素的额外间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594351/