使用 CSS 按比例调整图片大小

cssweb developmentfront end technology更新于 2024/4/16 5:00:17

为了使应用程序具有响应式设计,我们还需要使图片具有响应式功能。如果图片不具有响应式设计,应用程序就会出现溢出,效果会更糟糕。

因此,我们还需要根据父元素的尺寸按比例增加或减少图片的尺寸。在这里,我们将学习使用 CSS 按比例调整图片大小的各种方法。

语法

用户可以按照以下语法,使用 CSS 属性"width"按比例调整图片大小。

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

在上述语法中,我们为图片设置了 100% 的宽度和自动高度,使其具有响应式功能。

示例

在下面的示例中,我们创建了一个 div 元素,并赋予其"image"类名,并在 div 元素内部添加了一个图像作为子元素。

在 CSS 中,我们以百分比形式设置了 div 元素的宽度,该宽度等于总宽度的 30%。此外,我们还为图像设置了 100% 的宽度和自动高度。用户可以更改屏幕尺寸,并观察到图像尺寸会根据屏幕尺寸按比例缩小或增大。

<html>
<head>
   <style>
      .image {
         width: 30%;
         margin: 0 auto;
         border: 3px solid red;
         padding: 10px;
      }
      img {
         width: 100%;
         height: auto;
      }
   </style>
</head>
<body>
   <h2> Using the <i> width CSS property </i> to resize image proportionally </h2>
   <div class = "image">
      <img src = "https://www.cainiaomax.com/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

示例

在下面的示例中,我们使用了"object-fit: contain"CSS 属性按比例缩小图像的尺寸。这里,我们设置了图像父级 div 元素的比例宽度。此外,我们还对"img"元素使用了"object-fit: contain"CSS 属性。在输出中,用户可以观察到图像是响应式的,其尺寸会根据 div 元素的尺寸而变化。

<html>
<head>
   <style>
      .image {
         width: 30%;
         margin: 0 auto;
         border: 3px solid red;
         padding: 10px;
      }
      img {
         width: 100%;
         height: 50%;
         object-fit: contain;
      }
   </style>
</head>
<body>
   <h3> Using the <i> object-fit: contain CSS property </i> to resize image proportionally </h3>
   <div class = "image">
      <img src = "https://www.cainiaomax.com/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

示例

在下面的示例中,我们使用了 CSS 属性"background-size"按比例更改图像的尺寸。这里,我们设置了 div 元素的背景图像。此外,我们还使用了"contain"作为 CSS 属性"background-size"的值。它将图像分散到整个 div 中。如果 div 元素的尺寸增加,图像尺寸也会增加。如果 div 元素的尺寸减小,图像尺寸也会减小。

<html>
<head>
   <style>
      .image {
         width: 30%;
         min-height: 30%;
         margin: 0 auto;
         border: 3px solid red;
         padding: 10px;
         background-image: url("https://www.cainiaomax.com/python_pillow/images/tutorials_point.jpg");
         background-size: contain;
         background-repeat: no-repeat;
      }
   </style>
</head>
<body>
   <h3> Using the <i> background-size CSS property </i> to resize image proportionally </h3>
   <div class = "image"></div>
</body>
</html>

用户学会了按比例更改图片尺寸。在这里,我们只需以百分比(而不是像素或 rem)设置图片尺寸即可。此外,用户还可以使用 CSS 属性"background-size"按比例更改背景图片的尺寸。


相关文章


有用资源