如何使用 CSS 將 <img> 或 <video> 調整大小以適應其容器?
在網站上新增圖片的目的是為了提高其視覺吸引力和使用者吸引力。但是,如果我們無法控制網站上圖片的大小,它們就不會那麼吸引人。幸運的是,CSS 使更改圖片大小變得非常簡單。
可以使用多種方法更改 CSS 圖片大小。首先,讓我們檢查一下在 CSS 中更改圖片大小為何重要。如果圖片大小沒有限制,它將填充其大小的每個畫素。但是,每個圖片都應該適合其放置的容器內。這在構建響應式網站時尤其重要。
CSS object-fit 屬性
可以使用CSS object-fit 屬性將圖片或影片縮放以適應其內容框。此屬性以多種方式指定如何填充內容框或容器中的內容,例如保持縱橫比或透過擴充套件和向上提升儘可能多地填充空間等。object-position 屬性允許您修改替換元素的內容物件在其元素框內的對齊位置。
語法
以下是 object-fit 屬性的語法:
object-fit: fill|contain|cover|scale-down|none|initial|inherit;
示例
讓我們看下面的示例,我們將在這裡使用 CSS object-fit 屬性以及 fill 值。
<!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.tw/cg/images/logo.png">
</body>
</html>
當我們執行上述程式碼時,它將生成一個輸出,其中包含網頁上顯示的圖片和文字。
示例
考慮另一種情況,我們將在這裡使用 CSS object-fit 屬性以及 contain 值。
<!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.tw/cg/images/logo.png">
</body>
</html>
執行上述程式碼後,輸出視窗將彈出,在網頁上顯示圖片和文字。
示例
在下面的示例中,我們將使用 CSS object-fit 屬性以及 cover 值。
<!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>
當我們執行上述程式碼時,它將生成一個輸出,其中包含網頁上顯示的圖片和文字。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP