How to Apply CSS3 Transforms to Background Images

CSS3 Transforms on Background Images

Updated version of article published on September 27, 2012. Updates include latest data on current browser support, removing unnecessary vendor prefixes from code samples, and addition of live demo on CodePen.

Scaling, skewing and rotating any element is possible with the CSS3 transform property. It’s supported in all modern browsers without vendor prefixes. If you need to support Blackberry Browser and UC Browser for Android, you’ll need to use the -webkit- prefix, e.g.

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

Transforming the Background Only

The container element can have any styles applied but it must be set to position: relative since our pseudo element will be positioned within it. You should also set overflow: hidden unless you’re happy for the background to spill out beyond the container.

[code language=”css”]
#myelement {
position: relative;
overflow: hidden;
}
[/code]

We can now create an absolutely-positioned pseudo element with a transformed background. The z-index is set to -1 to ensure it appears below the container’s content.

[code language=”css”]
#myelement:before {
content: “”;
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(background.png) 0 0 repeat;
-webkit-transform: rotate(30deg);
transform: rotate(30deg);
}
[/code]

Note you may need to adjust the pseudo element’s width, height and position. For example, if you’re using a repeated image, a rotated area must be larger than its container to fully cover the background:

CSS3 transformation on background

Fixing the Background on a Transformed Element

Continue reading %How to Apply CSS3 Transforms to Background Images%


Source: Sitepoint