Improper use of CSS background-size

Web Development

Order and omissions matter when it comes to CSS. Until recently there was a quirk in the WebKit rendering engine related to the shorthand background property. The good news is that it has been fixed; the bad news is that it potentially breaks legacy code. If the background-size property is set prior to declaring background property it no longer behaves in the same fashion. The simplest solution is to declare the size of a background image in the background property.

code:

a.icon.good2 {
	background: #215387 url(test-sprite@2x.png) 4px -6px / 40px 82px no-repeat;
	}

Note: Including the size in the background property is not supported in older browsers. See example 2 below for a more backwards compatible solution.

Issue:

The W3C spec for the background shorthand property specifies that when declared without a size property it initializes size to ‘background-size: auto auto;’. Previously there was quirk with WebKit where if size was omitted it just didn’t initialize the size property for the background. This allowed for a previously declared background-size declaration to remain intact, displaying the image at its proper size. This quirk has since been removed and the latest release of WebKit now follows the W3C spec.

Bad code

a.icon {
	background-size: 40px 82px;
	}
a.icon.bad {
	background: #215387 url(test-sprite@2x.png) 4px -6px no-repeat;
	}

Produces

Solution

1. Add size to the background short-hand property and eliminate the background-size property

Code

a.icon.good2 {
     background: #215387 url(test-sprite@2x.png) 4px -6px / 40px 82px no-repeat;
}

Produces

2. If you must resize a background-image via a background-size property declare background size after the background property so it isn’t overridden.

Code

a.icon.good {
	background: #215387 url(test-sprite@2x.png) 4px -6px no-repeat;
	}
a.icon.good {
	background-size: 40px 82px;
	}

Produces

References:

http://www.w3.org/TR/css3-background/#the-background
https://bugs.webkit.org/show_bug.cgi?id=97761
http://lists.w3.org/Archives/Public/www-style/2012Oct/0112.html
http://caniuse.com/#search=background-size

About Rory C-B

Rory is a part of the Website Relations team. He works with the BlackBerry Browser team to ensure you receive the best possible experience when surfing the 'net. He can also be found haunting the developer forums, contributing to bbUI.js and on Twitter (@roryboy).

Join the conversation

Show comments Hide comments
+ -
blog comments powered by Disqus