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

今年稍早,WebKit 更新了 CSS background 簡寫屬性的行為。在這個變更之後,如果 background 速記符號屬性未在速記符號宣告中設定,則會將 background-size 重設為預設值 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 像素 x 40 像素)。

現有程式碼的修正

有幾種方法可以輕鬆解決這個問題:

  • 請使用 background-image,而不要使用 background 簡寫屬性。
  • 請最後設定 background-size,其特異性應高於在該元素上設定 background 的任何其他 CSS 規則,也別忘了檢查 :hover 規則。
  • !important 屬性套用至 background-size
  • 將大小資訊移至 background 速記屬性。

額外步驟:背景圖片偏移

除了這項變更之外,現在在背景中放置圖片時,也能享有更大的彈性。過去,您只能指定圖片相對於左上角的位置,現在您可以指定圖片相對於容器邊緣的偏移量。舉例來說,如果設定為 background-position: right 5px bottom 5px;,圖片會位於右邊緣和底部各 5 像素的位置。請參閱這個JSBin 上的範例