background-size與背景圖片填滿div
在開發中,常有需要將一張圖片作為一個div的背景圖片充滿div的需求
background-size的取值及解釋
background-size共有三種屬性,分別為
background-size: cover
MDN文檔解釋說明:縮放背景圖片以完全覆蓋背景區,可能背景圖片部分看不見。A keyword that is the inverse of contain. Scales the image as large as possible andmaintains image aspect ratio
(image doesn't get squished). The image "covers" the entire width or height of the container. When the image and container have different dimensions,the image is clipped either left/right or top/bottom.
這里的關鍵說明在於標紅的兩個區域,分別是它會保持圖片的寬高比
和當圖像和容器具有不同的尺寸時,圖像被左/右或頂部/底部裁剪。
之后會結合例子說明
background-size: contain
MDN文檔解釋說明:縮放背景圖片以完全裝入背景區,可能背景區部分空白。A keyword that scales the image as large as possible andmaintains image aspect ratio
(image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions,the empty areas (either top/bottom of left/right) are filled with the background-color.
這里的關鍵說明在於標紅的兩個區域,分別是它會保持圖片的寬高比
和當圖像和容器具有不同的尺寸時,空區域(左/右/上/右)填充背景色。
之后會結合例子說明
background-size: width-value,height-value;
分為固定大小
和百分比
和auto
,固定大小就是寫死;auto就是以背景圖片的比例縮放背景圖片。。
百分比的的MDN文檔解釋說明<percentage> 值,指定背景圖片相對背景區
(background positioning area)的百分比。背景區由background-origin設置
,默認為盒模型的內容區與內邊距,也可設置為只有內容區,或者還包括邊框。如果attachment 為fixed,背景區為瀏覽器可視區(即視口),不包括滾動條。不能為負值。
實驗及聲明
這次選用魯殿作為背景圖,這張圖的尺寸是260*234
,寬高比為260/234 ≈ 1.11
假設一div的寬高為200*200,下面測試中左為表現圖,右為原圖
background-size: contain
background-size: cover
background-size: auto (auto)
background-size: 100% 100%
分析及解釋:首先contain
是不行的,原理在於contain要保持寬高比將圖片完全放入div中
,div為200×200。原圖為260×234,所以為了放入div,寬260→200
,那么高就得200/寬高比(1.11) = 180
,所以會有下面的空白。
再其次,cover在這個時候也是不符合要求的,雖然看起來貌似符合要求,但是與原圖是有差別的嗎,原因在於cover與contain完全放入相反,它要求完全覆蓋。所以要覆蓋就要從更小的高計算。高234→200
,寬就等於200×1.11 = 222
,圖像就會被右部裁剪掉一部分。
再再其次,auto是原圖大小也是不符合的。
所以,
background-size: 100%, 100%;
是符合需求的。按照div的大小進行計算
其他各種大小div與各種大小的圖片搭配請參照上述說明自行分析。
個人建議這種需求都使用background-size: 100%, 100%;
本文轉載於:猿2048https://www.mk2048.com/blog/blog_hkhbi0ci20j.html