【问题标题】:Css clip image then resizeCss剪辑图像然后调整大小
【发布时间】:2018-05-17 05:10:39
【问题描述】:

我得到了一张大图,其中包含用于悬停更改的不同元素。 图片很大,所以我想剪下部分图片然后调整大小。

img {
  clip: rect(0px, 1124px, 186px, 38px);
  width:500px;
  height:auto;
  position:absolute;
}

但是,最终结果中显示的图像只是在 1124 像素边界处截取的图像的一个小版本。 (它甚至没有)因为我将它设置为 500 像素。 但我想要的只是将图像的裁剪部分调整为宽度为 500 像素。

什么是最好的解决方案?

在以下位置用视觉效果进行了解释: https://jsfiddle.net/0m939vmn/

【问题讨论】:

  • 你能用你正在处理的示例 html 发布一个正确的代码吗?
  • @HarshitDamani 使用 jsfiddle 更新

  • 可选坐标

标签: css image resize clip


【解决方案1】:

今天,您可以使用object-fitobject-position 来实现这一点,position 是可选的:

img {
  object-fit: none;
  /* will not be resized */
  object-position: 0 0;
  /* clip to your coordonates*/
  width: 500px;
  height: auto;
}

img+img {
  object-fit: none;
  /* will not be resized */
  object-position: 0 -1050px;
  /* clip to your coordonates*/
}

img+img+img {
  object-fit: none;
  /* will not be resized */
  object-position: -1050px -1050px;
  /* clip to your coordonates*/
}

img+img+img+img {
  object-fit: none;
  /* will not be resized */
  object-position: -1050px 0;
  /* clip to your coordonates*/
}
img+img+img+img+img {
  object-fit: none;
  /* will not be resized */
  object-position: 50% 50%;
  /* clip to your coordonates*/
}
the following image has width and height of 2000px.<br /> I'd like to have the red square only at a width and height of 500px.
<br />
<br />

<img src='https://s14-eu5.ixquick.com/cgi-bin/serveimage?
url=https%3A%2F%2Fvignette.wikia.nocookie.net%2Fmalware%2Fimages%2Fb%2Fba%2FWindows.png%2Frevision%2Flatest%3Fcb%3D20150730065805&sp=6789a53a9c28eb071f118bf9d294ffe0' />
<img src='https://s14-eu5.ixquick.com/cgi-bin/serveimage?
url=https%3A%2F%2Fvignette.wikia.nocookie.net%2Fmalware%2Fimages%2Fb%2Fba%2FWindows.png%2Frevision%2Flatest%3Fcb%3D20150730065805&sp=6789a53a9c28eb071f118bf9d294ffe0' />
<img src='https://s14-eu5.ixquick.com/cgi-bin/serveimage?
url=https%3A%2F%2Fvignette.wikia.nocookie.net%2Fmalware%2Fimages%2Fb%2Fba%2FWindows.png%2Frevision%2Flatest%3Fcb%3D20150730065805&sp=6789a53a9c28eb071f118bf9d294ffe0' />
<img src='https://s14-eu5.ixquick.com/cgi-bin/serveimage?
url=https%3A%2F%2Fvignette.wikia.nocookie.net%2Fmalware%2Fimages%2Fb%2Fba%2FWindows.png%2Frevision%2Flatest%3Fcb%3D20150730065805&sp=6789a53a9c28eb071f118bf9d294ffe0' />
<img src='https://s14-eu5.ixquick.com/cgi-bin/serveimage?
url=https%3A%2F%2Fvignette.wikia.nocookie.net%2Fmalware%2Fimages%2Fb%2Fba%2FWindows.png%2Frevision%2Flatest%3Fcb%3D20150730065805&sp=6789a53a9c28eb071f118bf9d294ffe0' />

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

object-fit CSS 属性指定应如何调整替换元素(例如 &lt;img&gt;&lt;video&gt;)的大小以适合其容器。


https://developer.mozilla.org/en-US/docs/Web/CSS/object-position

object-position CSS 属性确定所选元素在其框内的对齐方式。


要剪辑和调整大小,在clip() 旁边,您需要使用背景位置和背景大小来丢失img 标签。或在 div 中调整大小和组合 img 并作为最简单的方法溢出,我不发布示例,因为我相信您可以或已经弄清楚了这些..

【讨论】:

  • @VXp 大声笑,这就是它的意义......它是小提琴操作的复制/粘贴,并且没有告知使用的文档类型。不过这不会有什么坏处,浏览器足够聪明,可以纠正那些无臂的错别字。