Blog Posted July 15, 2011

CSS3: Using Transform to Make a Cube

CSS transforms! The following works in IE9 and above, as well as modern versions of Firefox, Safari, Chrome, and Opera. There's probably a trickier way this could be done with less markup, leveraging the :before and :after pseudo classes.

Example

The HTML

1
2
3
4
5
<div class="cube">
  <div class="cube-side top"></div>
  <div class="cube-side left"></div>
  <div class="cube-side right"></div>
</div>

The CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* a container div */
div.cube {
  position:relative;
  width:200px;
  height:220px;
}

/* styles for all the cube's sides (top, left, and right) */
div.cube-side {
  width:100px;
  height:100px;
  position:absolute;
}

/* the cube's top side */
div.top {
  left:50px;
  top:10px;
  background:#612d2d;
  -moz-transform:
    rotate(60deg)
    skew(0deg, -30deg)
    scale(1, 1.15);
  -webkit-transform:
    rotate(60deg)
    skew(0deg, -30deg)
    scale(1, 1.15);
  -o-transform:
    rotate(60deg)
    skew(0deg, -30deg)
    scale(1, 1.15);
  -ie-transform:
    rotate(60deg)
    skew(0deg, -30deg)
    scale(1, 1.15);
  transform:
    rotate(60deg)
    skew(0deg, -30deg)
    scale(1, 1.15);
}

/* the cube's left side */
div.left {
  background:#b06969;
  top:90px;
  left:0px;
  -moz-transform:skew(0deg, 30deg);
  -webkit-transform:skew(0deg, 30deg);
  -o-transform:skew(0deg, 30deg);
  -ie-transform:skew(0deg, 30deg);
  transform:skew(0deg, 30deg);
}

/* the cube's right side */
div.right {
  background:#b07c7c;
  top:90px;
  right:0;
  -moz-transform:skew(0deg, -30deg);
  -webkit-transform:skew(0deg, -30deg);
  -o-transform:skew(0deg, -30deg);
  -ie-transform:skew(0deg, -30deg);
  transform:skew(0deg, -30deg);
}