CSS transformations are really cool, but they don’t yet apply to background images. This article presents a neat workaround for those times when you really do want to rotate a background image, or to keep a background image fixed while its container element is rotate.
This article was updated in 2018.
Interested in mastering CSS3 like a pro? CSS Master, by Tiffany Brown, is available for download to all SitePoint Premium members. Alternatively, you can grab your copy of the book for just $19.
Scaling, skewing and rotating any element is possible with the CSS3
transform property. It’s supported in all modern browsers without vendor prefixes. (I’ve added in the
-webkit- just in case you want to support some older browsers.)
Great stuff. However, this rotates the whole element — its content, border and background image. What if you only want to rotate the background image? Or what if you want the background to remain fixed while the element is rotated?
Currently, there’s no W3C proposal for background-image transformations. It would be incredibly useful, so I suspect one will appear eventually, but that doesn’t help developers who want to use similar effects today.
Fortunately, there is a solution. In essence, it’s a hack which applies the background image to a
after pseudo element rather than the parent container. The pseudo element can then be transformed independently.