【问题标题】:How to automatically crop and center an image in div container如何在 div 容器中自动裁剪和居中图像
【发布时间】:2021-08-14 04:17:25
【问题描述】:

这是我的html代码

<div><img src="picture1.jpg" /></div>
<div><img src="picture2.jpg" /></div>
<div><img src="picture3.jpg" /></div>

我的 div 容器有一定的固定尺寸:

div{
    width: 400px;
    height: 400px;
    object-fit: cover;
    overflow: hidden;
}
img{
    height:100%;
    width: 100%;
    display: block;
}

我想在 div 容器内尽可能多地显示图像的中间部分(并将图像的其余部分裁剪掉)。因此,根据图像的尺寸,我想从图像的左右或顶部和底部裁剪一点。这样就可以显示图像中最大的正方形。这个正方形应该居中,当然也相应地缩放。

我之前尝试了很多并且阅读了很多线程。例如this one。问题是,对于不同的图像尺寸,没有什么对我有用(请记住,我不想为不同的图像调整代码)。我想要一个所有人的代码!

html 代码应保持原样。只有 css 应进行调整以使其工作(所以我不想使用背景图像)。但我对最先进的 CSS 东西持开放态度。使用 flex 布局或任何你想要的!

【问题讨论】:

  • object-fit: cover; -> 裁剪或object-fit: contain; 显示完整图像
  • ` max-width:100%;` 应该这样做
  • @ZohirSalak 我不是为我做的。我应该拥有或删除哪些其他属性?我想保持图像的原始比例,并且希望显示居中的正方形(不是最左边的那个)。

标签: html css image scale center


【解决方案1】:

object-fit: cover; 添加到图像以填充给定大小,同时不拉伸图像。还可以使用height: 100%; width: 100%; 确保图像只占用给定的空间。

图片默认居中。

img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

/* for demonstration only */

div {
  margin-bottom: 20px;
}

div:nth-of-type(1) {
  width: 200px;
  height: 50px;
}

div:nth-of-type(2) {
  width: 200px;
  height: 100px;
}

div:nth-of-type(3) {
  width: 200px;
  height: 200px;
}
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>

【讨论】:

    【解决方案2】:

    我的解决方案很简单:

    div {
      width: 200px; /* or whatever size you need */
      height: 200px; /* or whatever size you need */
      position: relative;
      overflow: hidden;
    }
    
    div img {
      max-width: 100%;
      height: auto;
      display: block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    &lt;div&gt;&lt;img src="https://via.placeholder.com/300x600.jpg"&gt;&lt;/div&gt;

    此解决方案的坏处是,如果任何图像具有非常不同的比例。在这种情况下,最小高度(例如)与相同大小的 div 的组合是必要的。

    【讨论】:

    • 太复杂了,并不能确保图像实际上会占用所有可用空间。如果图像的高度小于包装 div,那么您将获得空白。你也最有可能溢出父母。与object-fit 相比,它过于复杂了一个实际的简单解决方案。
    • PS:我编辑了您的问题以包含可重现的代码 sn-p。还修复了您的评论。 // 不是 CSS 或 HTML 的有效评论。对于 CSS /* comment */ 必须使用。 // 只是 JS 可用的一行注释
    • 正如我所说:根据图像的比例,它可能会导致问题。没有必要投反对票。此外,object-fit 在浏览器中具有很好的百分比,但仍不是 100%。
    • 唯一不支持object-fit的浏览器是IE11。 IE13 和 IE19 没有问题。 IE 将于 2021 年 8 月 17 日被微软淘汰。否决票是因为不必要地使问题复杂化。实际上没有理由让一个真正简单的解决方案过于复杂,只是为了支持一个不会出现超过 3 个月的旧浏览器。
    猜你喜欢
    • 2012-07-18
    • 2013-12-24
    • 2013-08-17
    • 1970-01-01
    • 2021-06-05
    • 2016-11-27
    • 2019-12-10
    • 2013-07-18
    相关资源
    最近更新 更多