Monday, July 30, 2018

How to Apply CSS3 Transforms to Background Images

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.)

[code language="css"]
#myelement {
-webkit-transform: rotate(30deg);
transform: rotate(30deg);
}
[/code]

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 before or after pseudo element rather than the parent container. The pseudo element can then be transformed independently.

The post How to Apply CSS3 Transforms to Background Images appeared first on SitePoint.


by Craig Buckler via SitePoint

No comments:

Post a Comment