移动 WebKit 浏览器即将推出 CSS 背景简写功能

今年早些时候,WebKit 更新了 CSS background 缩写属性的行为。经过此更改,如果 background-size 未在缩写声明中设置,background 缩写属性将将其重置为默认值 auto auto。此项更改使 Chrome 和其他 WebKit 浏览器符合规范,并与 Firefox、Opera 和 Internet Explorer 的行为保持一致。

随着 Chrome(Android 版)开始采用 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(50px 40px)。

现有代码的修复

您可以通过以下几种方法轻松解决此问题:

  • 使用 background-image,而不要使用 background 缩写属性。
  • 最后设置 background-size,其特异性高于对该元素设置 background 的任何其他 CSS 规则,同时别忘了检查 :hover 规则。
  • !important 属性应用于 background-size
  • 将尺寸信息移至 background 缩写属性。

额外知识点:背景图片偏移

除了这项更改之外,您现在还可以更灵活地在背景中放置图片。以前,您只能指定相对于左上角的图片位置,现在您可以指定相对于容器边缘的偏移量。例如,设置 background-position: right 5px bottom 5px; 后,图片将位于距离右边缘 5 像素和距离底部 5 像素的位置。请查看 JSBin 上的示例