How to use CSS Grid and Flexbox In Javascript
In this approach, we leverage CSS Grid and Flexbox to lay out the cube’s faces and control their positioning. JavaScript is used to manage user interaction to rotate the cube and trigger animations. This approach offers a modern and responsive solution for creating complex layouts.
Example: The below code implements above-approach to create a viewer cube.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>CSS Viewer Cube</title>
<link rel="stylesheet" href="style.css">
</head>
<body style="text-align: center;">
<h2>
Below is the CSS viewer cube
created using JavaScript
</h2>
<div class="cube-container">
<div class="cube">
<div class="face front">Front</div>
<div class="face back">Back</div>
<div class="face right">Right</div>
<div class="face left">Left</div>
<div class="face top">Top</div>
<div class="face bottom">Bottom</div>
</div>
</div>
<script>
const cube = document.
querySelector('.cube');
let rotateX = 0;
let rotateY = 0;
function rotateCube() {
rotateX += 1;
rotateY += 1;
cube.style.transform =
`rotateX(${rotateX}deg)
rotateY(${rotateY}deg)`;
}
setInterval(rotateCube, 50);
</script>
</body>
</html>
.cube-container {
width: 320px;
height: 320px;
perspective: 1000px;
margin: auto;
}
.cube {
width: 100%;
height: 100%;
display: grid;
position: relative;
transform-style: preserve-3d;
animation: rotate-cube 5s linear infinite;
}
.face {
position: absolute;
width: 100px;
height: 100px;
background-color: #ddd;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}
.front {
transform: translateZ(50px);
}
.back {
transform: rotateY(180deg) translateZ(50px);
}
.right {
transform: rotateY(90deg) translateZ(50px);
}
.left {
transform: rotateY(-90deg) translateZ(50px);
}
.top {
transform: rotateX(90deg) translateZ(50px);
}
.bottom {
transform: rotateX(-90deg) translateZ(50px);
}
@keyframes rotate-cube {
from {
transform: rotateY(0);
}
to {
transform: rotateY(360deg);
}
}
Output:
CSS Viewer Cube without Three.js using Vanilla JavaScript
Creating a CSS viewer cube without three.js using Vanilla JavaScript offers a lightweight alternative for rendering 3D cubes in web applications. This article explores various approaches to implementing a CSS viewer cube without relying on three.js, providing developers with flexibility and simplicity.
These are the following approaches:
Table of Content
- Creating Cube with HTML and CSS
- Using CSS Transforms and Transitions
- Using CSS Grid and Flexbox