将裁剪后的图像缩放到屏幕宽度

时间:2021-06-23 10:20:48

标签: html css

我可以使用

裁剪图像

<img
 src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Oryctolagus_cuniculus_Tasmania_2.jpg/800px-Oryctolagus_cuniculus_Tasmania_2.jpg" 

 style="width: 200px; height: 200px; object-fit: none; object-position: -350px -300px">

我现在如何将图像缩放到封闭容器的(未知)宽度?

2 个答案:

答案 0 :(得分:0)

您可以使用视图高度(vh) 和视图宽度(vw) 代替静态像素,这样无论您打开哪个屏幕,图片都会具有相同的大小。

答案 1 :(得分:0)

我们知道,当容器宽度为 200 像素时,图像必须移动 -365 像素和 -300 像素。

我们还知道(通过检查)img 的自然宽度和高度(这是问题中给出的代码中默认使用的宽度和高度)是 800px x 1000px。

此代码段将这些度量设置为 CSS 变量。

然后它使用一个 div 而不是一个 img(因为被替换的元素不能在元素之后有伪元素),给它一个缩放后的方形裁剪图像的宽度和高度,以及一个将整个图像作为背景的伪元素,然后翻译到正确的位置。

.container {
  width: 25vw; /* could be anything */
  height: 30vh;
}
.croppedimg {
  /* these all in the same units (px was used in the question) */
  --originalW: 800; /* the natural (original) width of the img */
  --originalH: 1000; /* ditto height */
  --cutoutLeft: -365; /* amount needed to move left to crop */
  --cutoutTop: -300; /* amount needed to move top to crop */
  --cutout: 200; /* length of side of the square */

  width: 100%;
  height: 0;
  padding-bottom: 100%; /* this gives us a square */
  position: relative;
  overflow: hidden;
}
.croppedimg::after {
  content: '';
  /* has same aspect ratio as the original image */
  width: calc((var(--originalW) / var(--cutout)) * 100%);
  height:  calc((var(--originalH) / var(--cutout)) * 100%);
  position: absolute;
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Oryctolagus_cuniculus_Tasmania_2.jpg/800px-Oryctolagus_cuniculus_Tasmania_2.jpg);
  background-size: 100% auto;
  background-repeat: no-repeat no-repeat;
  transform: translateX(calc((-365 / 800) * 100%)) translateY(calc((-300 / 1000) * 100%)); 
}
<div class="container">
  <div class="croppedimg"></div>
</div>