gaintsev
5/5/2016 - 3:00 PM

A simple snippet which allows to build a CSS 3D box with the given dimensions. Used PostCSS and CSSNext.

A simple snippet which allows to build a CSS 3D box with the given dimensions. Used PostCSS and CSSNext.

/*
  A simple snippet which allows to build a CSS 3D box with the given dimensions.
  Used PostCSS and CSSNext.
  Source: https://gist.github.com/gaintsev/e054f05fb67909a82244fd5e026b377a
*/

:root {
  /*Set Box Sizes*/
  --boxWidth: 260px;
  --boxHeight: 400px;
  --boxLength: 80px;
}

.box-container {

  width: var(--boxWidth);
  height: var(--boxHeight);
  position: relative;
  perspective: 1000px;

  & .box {

    width: 100%;
    height: 100%;
    position: absolute;
    transform-style: preserve-3d;
    transition-duration: 1s;

    &.show-front {
      transform: translateZ(0);
    }

    &.show-back {
      transform: rotateY(180deg);
    }

    &.show-left {
      transform: rotateY(90deg);
    }

    &.show-right {
      transform: rotateY(-90deg);
    }

    &.show-top {
      transform: rotateX(-90deg);
    }

    &.show-bottom {
      transform: rotateX(90deg);
    }

    & figure {

      margin: 0;
      display: block;
      position: absolute;
      box-shadow: 0 0 20px rgba(0, 0, 0, .2) inset;

      &.front {
        width: var(--boxWidth);
        height: var(--boxHeight);
        transform: rotateY(0deg) translateZ(calc(var(--boxLength) / 2));
      }
      &.back {
        width: var(--boxWidth);
        height: var(--boxHeight);
        transform: rotateX(180deg) translateZ(calc(var(--boxLength) / 2)) scaleX(-1) scaleY(-1);
      }
      &.left {
        width: var(--boxLength);
        height: var(--boxHeight);
        left: calc((var(--boxWidth) - var(--boxLength)) / 2);
        transform: rotateY( -90deg) translateZ(calc(var(--boxWidth) / 2));
      }
      &.right {
        width: var(--boxLength);
        height: var(--boxHeight);
        left: calc((var(--boxWidth) - var(--boxLength)) / 2);
        transform: rotateY(90deg) translateZ(calc(var(--boxWidth) / 2));
      }
      &.top {
        width: var(--boxWidth);
        height: var(--boxLength);
        top: calc((var(--boxHeight) - var(--boxLength)) / 2);
        transform: rotateX(90deg) translateZ(calc(var(--boxHeight) / 2));
      }
      &.bottom {
        width: var(--boxWidth);
        height: var(--boxLength);
        top: calc((var(--boxHeight) - var(--boxLength)) / 2);
        transform: rotateX( -90deg) translateZ(calc(var(--boxHeight) / 2));
      }

    }

  }

}