在 CSS3 之前,background 一個元素只能有一張背景圖,想疊多層就得包好幾個 div。CSS3 直接把這件事變簡單了。
background: 背景層1, 背景層2, 背景層3;
各層以逗號分隔,最左邊(寫在最前面)的是最上層,往後依序堆疊。
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;
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-position 值。有幾張圖,就必須寫幾組座標,順序要與圖片清單一致,否則會錯位。
若某個屬性所有層都相同(例如都不重複),可以只寫一個值套用到全部;但位置幾乎不可能相同,所以務必逐層寫明。
repeat)與一張不規則裝飾圖(no-repeat)。linear-gradient 畫出純 CSS 的棋盤格或條紋背景,完全不需要圖片。最後一點值得特別一提:以 linear-gradient 疊出的斜線格紋,是多重背景最漂亮的應用之一,例如 background: repeating-linear-gradient(45deg, #eee 0 10px, #fff 10px 20px); 就能得到斜條紋,檔案重量為零。