首页 > 解决方案 > 保持图像纵横比

问题描述

我目前正在重构我的网站并尝试摆脱一些断点。在我的投资组合中,我有一个图片库,其中显示 3x3 的图片拼贴。这些图块是用 css 网格构建的。我的示例中的图块应为 200 像素高和最小最大(200 像素,333 像素)宽度。

目前,瓷砖按预期工作。但是图像不保持它们的纵横比。有什么办法可以保持原始比例并将图像剪切到它们的高度?容器的最小版本应该是 200x200。

https://codepen.io/yanniksturm/pen/LYVegro

<div class="content">

  <div id="img1" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
  </div>
  <div id="img2" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
  </div>
  <div id="img3" class="imageWrapper">
<img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
  </div>

</div>

.content {
  min-width: 600px;
  max-width: 999px;
  margin: auto;
  width: 80%;
    backgeound-color: red;
  display: grid;
  grid-template-columns: minmax (200px, 333px) minmax (200px, 333px) minmax (200px, 333px);
  grid-template-rows: 200px;

}

.imageWrapper {
  height: 100%;
  width: 100%;

}

img {
   height: 100%;
  width: 100%;

}

#img1 {
  grid-column: 1;
}
#img2 {
 grid-column: 2;
}

#img3 {
  grid-column: 3;
}

非常感谢你的帮助!

标签: imagegrid-layoutaspect-ratio

解决方案


您需要将img宽度和高度设置为auto并添加一个max-width: 100%;以保持纵横比。

img {
  height: auto;
  width: auto;
  max-width: 100%;
}

请参见下面的片段。

您可以使用object-fit: cover;,但旧浏览器不支持(我正在查看 IE11)。

.content {
  min-width: 600px;
  max-width: 999px;
  margin: auto;
  width: 80%;
  backgeound-color: red;
  display: grid;
  grid-template-columns: minmax (200px, 333px) minmax (200px, 333px) minmax (200px, 333px);
  grid-template-rows: 200px;
}

.imageWrapper {
  height: 100%;
  width: 100%;
  border: 1px solid red;
}

img {
  height: auto;
  width: auto;
  max-width: 100%;
}

#img1 {
  grid-column: 1;
}

#img2 {
  grid-column: 2;
}

#img3 {
  grid-column: 3;
}
<div class="content">

  <div id="img1" class="imageWrapper">
    <img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
  </div>
  <div id="img2" class="imageWrapper">
    <img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
  </div>
  <div id="img3" class="imageWrapper">
    <img src="https://images.unsplash.com/photo-1562886889-4ff7af0602ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2089&q=80">
  </div>

</div>


推荐阅读