CSS cube slicing animation
by Julien Roche
HTML
<div class="cube">
<div class="cube__face cube__face--front"></div>
<div class="cube__face cube__face--back"></div>
<div class="cube__face cube__face--right"></div>
<div class="cube__face cube__face--left"></div>
</div>
<button type="button">rotate</button>
CSS
:root {
--rotate: 0deg;
}
html,
body {
height: 100%;
margin: 0 0 0 0;
padding: 0 0 0 0;
width: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.cube {
backface-visibility: visible;
height: 150px;
perspective-origin: 50px 50px;
perspective: 150px;
position: relative;
transform-style: preserve-3d;
width: 150px;
}
.cube__face {
background-repeat: no-repeat;
background-size: cover;
display: block;
position: absolute;
width: 100px;
height: 100px;
border: none;
line-height: 100px;
font-family: sans-serif;
font-size: 60px;
color: white;
text-align: center;
transition: transform 1s linear;
}
/* Define each face based on direction */
.cube__face--front {
background-image: url('https://images.unsplash.com/photo-1521579880562-101f47676ee1?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1b149040db05a369f39ef7d6f0170941&auto=format&fit=crop&w=1968&q=80');
transform: rotateY(calc(0deg + var(--rotate))) translateZ(50px);
}
.cube__face--back {
background-image: url('https://images.unsplash.com/photo-1501010624319-d28d01f59783?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=264acb48fe636caeef624c00dfa04214&auto=format&fit=crop&w=1350&q=80');
transform: rotateY(calc(180deg + var(--rotate))) translateZ(50px);
}
.cube__face--right {
background-image: url('https://images.unsplash.com/photo-1520709644167-e7e1b34482be?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1e55e4221a88c5fb1f69afa8a6f06ab9&auto=format&fit=crop&w=1350&q=80');
transform: rotateY(calc(90deg + var(--rotate))) translateZ(50px);
}
.cube__face--left {
background-image: url('https://images.unsplash.com/photo-1511891636602-1633aec7a560?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=38398322afe3f7b9a32c8ec72bf50837&auto=format&fit=crop&w=634&q=80');
transform: rotateY(calc(-90deg + var(--rotate))) translateZ(50px);
}
JavaScript 1.7
const rotateButton = document.querySelector('button');
const root = document.documentElement;
let deg = 0;
rotateButton.addEventListener(
'click',
(event) => {
deg += 90;
root.style.setProperty('--rotate', `${deg}deg`);
},
false
);