CSS3 Non rectangular backgrounds

Bored of rectangular backgrounds? You are right, squared divs are boring but you don't like rounded corners anymore and need something special like this?

This is a nice div with a non rectangular background!
Then, you have reached the right place!

This nice effect is obtained using the new CSS 3D transform, so no every browser will render this example properly, you won't see the example correctly if you don't use:

  • Chrome 12+
  • Firefox 10+
  • Internet Explorer 10+
  • Safari 4+

Creating a background layer

The first thing to do is creating a background which can be rotable or transformable without change the proportions of the actual div. We can get it using the :before selector, this will be our HTML:
This is a nice div with a non rectangular background!
And our base css:
.nonrectangular{ position:relative } 
 content: " "; 
Using .nonrectangular:before we create a virtual empty div with the same width and height inside the actual div. Making it absolute positioned, and its parent relative, we force our browser to redraw the before layer and it will visible, placed in the top left of the .nonrectangular div. The negative z-index property set our background layer up!

Setting the shape of the background

There is no way of making a non-paralelogram polygon using just 2D transformations, to obtain that great effect we need to add some perspective to our background. Currently, only Firefox (version 16) uses css transformations without vendor prefixes, so it is needed to add several rules to get a crossbrowser result:
 -webkit-transform: perspective(150px) rotate3D(0.5,-0.3,0.7,3deg); 
 -moz-transform: perspective(150px) rotate3D(0.5,-0.3,0.7,3deg);
 transform: perspective(150px) rotate3D(0.5,-0.3,0.7,3deg);
 -ms-transform: rotate(5deg) translate(-10px);
Different shapes can be obtained changing the values of the rotate3D property, so just play a little bit with them! The last rule is for IE9, which doesn't support 3D transformations but 2D, so we can rotate the background in order to give some nice effect using IE9 too.

If you want to play a little with this background trick here you have a jsfiddle.

© arqex 2023
we'll find ourselves
far, far away...
Transitions here have been created using a library of mine:
React interactable.
This awesome hyperspace effect thanks to this codepen from Noah Blon.
Software development can be fun!
Javier Márquez
Software developer