iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦒

Creating a Cube in 18 Lines of CSS

に公開

Introduction

I managed to create a cube with a number of lines that looks somewhat impressive.

Finished Product

CSS
.cube {
  display: grid;
  transform-style: preserve-3d;
  transform: rotateX(30deg) rotateY(30deg);
}

.cube__side {
  padding: 50px;
  grid-area: 1/ 1;
  box-shadow: inset 0 0 0 1px #000;
  transform: rotateX(var(--x, 0deg)) rotateY(var(--y, 0deg)) translateZ(var(--z, 50px));
}

.cube__side:nth-of-type(3n + 1) {--x: 90deg}

.cube__side:nth-of-type(3n + 2) {--y: 90deg}

.cube__side:nth-of-type(even) {--z: -50px}

Rough Explanation

Not using border for outlines

When using the border property, the shape breaks if the values are increased, so I used box-shadow instead.

The last three lines

I compressed the following CSS nicely to make it compact.

.cube__side {
  padding: 50px;
  grid-area: 1/ 1;
  box-shadow: inset 0 0 0 1px #000;
  transform: translateZ(var(--z, 50px));
}

.cube__side:nth-of-type(1),
.cube__side:nth-of-type(4) {
  transform: rotateX(90deg)  translateZ(var(--z, 50px));
}

.cube__side:nth-of-type(2),
.cube__side:nth-of-type(5) {
  transform: rotateY(90deg)  translateZ(var(--z, 50px));
}

.cube__side:nth-of-type(2),
.cube__side:nth-of-type(4),
.cube__side:nth-of-type(6) {
  --z: -50px
}

Conclusion

I used padding this time because there is no text inside the div, but please use width and height if you are going to include text.

Discussion