使用CSS等比例调整图像大小

使用CSS等比例调整图像大小

为了使应用程序具有响应式设计,我们还需要使图像具有响应式。如果图像不具有响应性,应用程序会出现溢出,看起来很糟糕。

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

语法

用户可以按照下面的语法使用’width’ CSS属性来等比例调整图像的大小。

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

在上述语法中,我们为图片设置了100%的宽度和自动高度,实现了响应式布局。

示例1

在下面的示例中,我们创建了一个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.tutorialspoint.com/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

示例2

在下面的示例中,我们使用了“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.tutorialspoint.com/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

示例3

在下面的示例中,我们使用了’background-size’ CSS属性按比例更改图像的尺寸。在这里,我们为div元素设置了背景图像。此外,我们还使用了’contain’作为’background-size’ CSS属性的值。它将图像平铺到整个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.tutorialspoint.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”来按比例更改背景图像的尺寸。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程

CSS 精选笔记