css background-size與背景圖片填滿div


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 and maintains 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 and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. www.97yingyuan.org 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,背景區為瀏覽器可視區(即視口),不包括滾動條。不能為負值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM