html - 在网格布局中添加到图形元素的额外间隙

标签 html css figure css-grid

我看到额外的空间被添加到网格元素,导致元素未对齐但无法弄清楚它来自哪里(边距,元素的填充无效,网格元素对齐以垂直和水平开始)。

编辑:我试图将包装大小限制为 820x410,这确实消除了差距。我知道网格列被拉伸(stretch)以填充包装器 div。虽然这可以解决问题,但我仍然不明白额外的垂直间隙是从哪里来的。

pixel perfect images inside figure elements

样式:

#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-gap10px 所以每一列都有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/

相关文章:

javascript - JQuery 调用基于 CSS 属性的点击

html - 在所有设备上具有全宽的并排框

javascript - 如何在 HTML 中制作 anchor 标记下拉列表

javascript - 如何在打印网页时将高度设置为自动

javascript - 使用独特的布局设计选择下拉菜单

php - 隐藏 Mailto : link

latex - 在包含制表符环境的图形周围创建一个框

MATLAB:提取与最大 y 值匹配的 x 坐标

html - 圆圈的 CSS 样式 <figure> 不会显示在打印 View 中

javascript - 已修复 : Why is my dynamic SELECT not working in IE9?