如何使用 CSS 创建自适应图像?
要创建一个自适应的图像,首先使用 <img> 元素设置一个图像。使用 width 和 max-width 属性将相同图像设置为自适应图像。
设置图像
要在网页上设置图像,请使用 <img> 元素。图像的链接包含在 <img> 元素的 src 属性中 −
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt ="Rail Track">
上面,我们还为替换文本使用了 alt 属性。
设置自适应性
将 width 设置为 100% 以将一个图像转换为自适应图像。另外,您还需要设置 max-width 属性 −
img {
width: 100%;
max-width: 1000px;
}
举例
以下是使用 CSS 创建自适应图像的代码 −
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img {
width: 100%;
max-width: 1000px;
}
</style>
</head>
<body>
<h1>Responsive Images Example</h1>
<h2>Resize the window to see responsive image scale up and down</h2>
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt ="Rail Track">
</body>
</html>
举例
让我们看看如何使用 width 和 height 属性使图像自适应 −
<!DOCTYPE html>
<html>
<head>
<style>
img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Responsive Images Example</h1>
<h2>Resize the window to see responsive image scale up and down</h2>
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt ="Rail Track">
</body>
</html>
举例
让我们看看如何使用 max-width 和 height 属性使图像自适应 −
<!DOCTYPE html>
<html>
<head>
<style>
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Responsive Images Example</h1>
<h2>Resize the window to see responsive image scale up and down</h2>
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt ="Rail Track">
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP