How to Apply CSS3 Transforms to Background Images

Original Source: https://www.sitepoint.com/css3-transform-background-image/?utm_source=rss

How to Apply CSS3 Transforms to Background Images

CSS transformations are great, but they don’t (yet?) apply to background images. This article presents a 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 rotated.

This article was updated in 2020.

Scaling, skewing, and rotating any element is possible with the CSS3 transform property. It’s supported in all modern browsers without vendor prefixes.

#myelement {
transform: rotate(30deg);
}

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 content is rotated?

There’s no W3C CSS proposal for background-image transformations. It would be incredibly useful, so perhaps one will appear eventually, but that doesn’t help developers who want to use similar effects today.

One option would be to create a new background image from the original, say rotated by 45 degrees. This could be achieved using:

a server-side image manipulation process
a client-side canvas-based image handling code, or
APIs provided by some image-hosting CDN services.

But all these require additional effort, processing, and costs.

Fortunately, there’s a CSS-based 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 of the content.

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

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *