CSS3 之前的 background 一次只能處理一張圖片,設定完背景圖、平鋪方式與位置就到極限了。CSS3 大幅擴權,讓單一元素可以疊放多張背景圖,這就是所謂的多重背景。
語法結構很單純,以逗號分隔每一層:
background: 背景, 背景, 背景;
實際寫法如下,用五層雲與雨的圖示拼出一個完整的天氣圖:
background: url(images/weather-cloud.png) center center no-repeat, url(images/weather-clouds.png) top left no-repeat, url(images/weather-cloudy.png) top right no-repeat, url(images/weather-rain.png) bottom left no-repeat, url(images/weather-snow.png) bottom right no-repeat;
這其實是 CSS2 的 background 升級而來,只是多支援了疊層。當然也可以拆開來寫:
background-image: url(images/weather-cloud.png), url(images/weather-clouds.png), url(images/weather-cloudy.png), url(images/weather-rain.png), url(images/weather-snow.png); background-repeat: no-repeat; background-position: center center, top left, top right, bottom left, bottom right;
這裡有個最容易出錯的地方:拆開寫時,各子屬性的值必須與 background-image 的層數、順序一一對應。如果某個屬性想讓所有層共用同一個值,寫一個即可(如上面的 background-repeat);但若各層需要不同設定,就必須逐層列出,不能省略。順序錯了,圖層就會跑到意料之外的位置。
多重背景的實用場景不少:卡片加上裝飾紋理、按鈕疊加漸層與圖示、容器同時呈現底色與花紋,都能省下額外的 DOM 包裝,讓結構更乾淨。