如何使用 CSS 调整
或
向网站添加图像的目的是提高其视觉吸引力和用户吸引力。但是,如果我们无法控制网站上图像的大小,它们就不会那么吸引人了。幸运的是,CSS 使更改图像大小变得非常简单。
可以使用多种方法更改 CSS 图像大小。首先,让我们检查一下为什么在 CSS 中更改图像大小很重要。如果没有对图像大小的限制,图像将填充其大小的每个像素。但是,每个图像都应该与其放置的容器大小相符。这在构建响应式网站时尤其重要。
CSS object-fit 属性
可以使用 **CSS object-fit 属性** 将图像或视频缩放以适应其内容框。此属性指定如何以多种方式填充内容框或容器中的内容,例如保持纵横比或通过扩展和提升尽可能多地填充空间等。object-position 属性允许您修改替换元素的内容对象在其元素框内的对齐位置。
语法
以下是 object-fit 属性的语法:
object-fit: fill|contain|cover|scale-down|none|initial|inherit;
示例
让我们来看下面的示例,我们将使用带有 fill 值的 CSS object-fit 属性。
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: verdana;
color: #DE3163;
background-color: #D5F5E3;
text-align: center;
}
#tp {
width: 400px;
height: 200px;
object-fit: fill;
}
</style>
</head>
<body>
<h2>CSS object-fit property with fill value</h2>
<img id="tp" src="https://tutorialspoint.com/cg/images/logo.png">
</body>
</html>
运行以上代码后,它将生成一个包含图像和网页上显示的文本的输出。
示例
考虑另一种情况,我们将使用带有 contain 值的 CSS object-fit 属性。
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: verdana;
font-size: 15px;
color: #DE3163;
background-color: #F4ECF7;
text-align: center;
}
#tp {
width: 500px;
height: 450px;
object-fit: contain;
}
</style>
</head>
<body>
<h2>CSS object-fit property with contain value</h2>
<img id="tp" src="https://tutorialspoint.com/cg/images/logo.png">
</body>
</html>
运行以上代码后,输出窗口将弹出,在网页上显示图像和文本。
示例
在下面的示例中,我们将使用带有 cover 值的 CSS object-fit 属性。
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: verdana;
color: #DE3163;
background-color: #D6EAF8;
text-align: center;
}
#tp {
width: 300px;
height: 200px;
object-fit: cover;
}
</style>
</head>
<body>
<h2>CSS object-fit property with cover value</h2>
<br>
<br>
<br>
<img id="tp" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Dhoni_behind_Stumps.jpg/330px-Dhoni_behind_Stumps.jpg">
</body>
</html>
运行以上代码后,它将生成一个包含图像和网页上显示的文本的输出。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP