一、使用max-widthmax-height

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

二、使用object-fit

object-fit属性允许您指定如何调整替换元素(如<img><video>)的内容大小以适应其容器。该属性可以接受以下值:

  • fill:使内容大小完全填充容器,可能会改变内容的大小和形状。
  • contain:保持内容的宽高比,使内容完全适应容器,可能会留下空白区域。
  • cover:保持内容的宽高比,并使内容完全覆盖容器,可能会裁剪内容。
  • none:保持内容的原始大小和形状,不进行任何缩放。

以下是一个使用object-fit: cover;的示例:

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

三、使用background-size

  • cover:保持宽高比,使背景图像覆盖整个元素。
  • contain:保持宽高比,使背景图像完整显示在元素内。
  • auto:保持原始尺寸。
  • <length>:指定背景图像的宽度和高度。

以下是一个使用background-size: cover;的示例:

.element {
  background-image: url('image.jpg');
  background-size: cover;
  background-position: center;
}

这个方法会使背景图像覆盖整个元素,同时保持图像的宽高比。

四、使用JavaScript

function resizeImage(img) {
  const ratio = Math.min(img.parentElement.clientWidth / img.width, img.parentElement.clientHeight / img.height);
  img.width = img.width * ratio;
  img.height = img.height * ratio;
}

window.onload = function() {
  const images = document.querySelectorAll('img');
  images.forEach(resizeImage);
};

这段代码会在页面加载时调整所有<img>标签的大小,以适应其容器。

总结