行動版 WebKit 瀏覽器專用的 CSS 背景簡寫

今年稍早,WebKit 更新 CSS background 簡寫屬性的行為。這項異動生效後,如果沒有在簡短宣告中設定 background-sizebackground 簡短屬性會將該值重設為預設值 auto auto。這項變更讓 Chrome 和其他 WebKit 瀏覽器以符合規格,以及 Firefox、Opera 和 Internet Explorer 的行為。

由於 Android 版 Chrome 要推進 WebKit 目前的版本,因此 Android 版推出了這項異動。由於 Webkit 修正了這個問題,因此利用多種瀏覽器測試的網站可能不會受到影響。

以前的舊工作方法

// background-size is reset to auto auto by the background shorthand
.foo {
    background-size: 50px 40px;
    background: url(foo.png) no-repeat;
}

background 簡寫屬性不含任何大小屬性,因此會將 background-size 重設為預設值 auto auto

正確的指定圖片大小

// background-size is specified after background
.fooA {
    background: url(foo.png) no-repeat;
    background-size: 50px 40px;
}

// background-size is specified inline after position
.fooB {
    background: url(foo.png) 0% / 50px 40px no-repeat;
}

fooB 中,如要指定 background 中的 background-size,必須先指定 position (0%),然後依序指定正斜線和 background-size (50 px 40px)。

修正現有程式碼

以下幾種方式可協助您輕鬆解決問題:

  • 使用 background-image 而非 background 簡寫屬性。
  • 最後設定 background-size,優先順序高於任何其他針對該元素設定 background 的 CSS 規則。別忘了檢查和 :hover 規則。
  • !important 屬性套用至 background-size
  • 將大小資訊移至 background 簡寫屬性。

額外獎勵:背景圖片位移

除了這項變動之外,您現在還可以更靈活地安排圖片在背景中的位置。過去,您只能指定從左上角算起的圖片位置,現在您可以指定與容器邊緣的偏移值。舉例來說,設定 background-position: right 5px bottom 5px; 時,圖片方向為距離右側 5 像素,距離底部 5 像素。查看這個 JSBin 範例