在 CSS2.1 時代,背景圖片尺寸無法直接調整,因此常必須依賴 repeat、repeat-x、repeat-y 或 no-repeat 來控制顯示方式。
CSS3 加入 background-size 後,可以明確指定背景圖片尺寸,讓背景填滿容器或避免重複。
/* 以像素指定 */
#bg1 {
background-size: 200px 100px;
}
/* 以百分比指定 */
#bg2 {
background-size: 30% 60%;
}
/* 等比放大填滿元素 */
#bg3 {
background-size: cover;
}
/* 等比縮小以完整顯示圖片 */
#bg4 {
background-size: contain;
}
/* 使用圖片原始尺寸 */
#bg5 {
background-size: auto;
}
若希望背景不規則重複,也可搭配 background-repeat: no-repeat 使用。實務上,cover 常用於視覺橫幅,contain 則適合需要完整呈現圖片的情境。