【问题标题】:Keep Image Ascpect Ratio保持图像纵横比
【发布时间】:2020-03-10 20:41:12
【问题描述】:

我目前正在重构我的网站并尝试摆脱一些断点。 在我的投资组合中,我有一个图片库,其中显示 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;
}

非常感谢您的帮助!

【问题讨论】:

标签: image grid-layout aspect-ratio


【解决方案1】:

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

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

参见下面的 sn-p。

您可以使用object-fit: cover;,但那是not supported in older browsers(我正在查看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>

【讨论】:

  • 幸运的是,我不必支持 IE11 ? object-fit: cover; 会为我工作。谢谢!