保持图像纵横比

时间:2020-03-10 12:17:34

标签: image grid-layout aspect-ratio

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

当前,图块按预期工作。但是图像不能保持其纵横比。有什么办法可以保持原始比例并以其高度剪切图像?容器的最小版本应为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;
}

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

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

请参见以下代码段。

您可以使用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>