如何使用 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