Creating Cube with HTML and CSS
In this approach, we’ll use HTML and CSS to define a simple 3D cube and rotate it using JavaScript. We create six div elements representing the six faces of the cube and apply CSS styling for position and transformation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>CSS 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">
<div class="face front">Front</div>
<div class="face back">Back</div>
<div class="face top">Top</div>
<div class="face bottom">Bottom</div>
<div class="face left">Left</div>
<div class="face right">Right</div>
</div>
<script>
const cube = document.querySelector('.cube');
function rotateCube() {
cube.style.transform += ' rotateY(1deg)';
}
setInterval(rotateCube, 50);
</script>
</body>
</html>
.cube {
position: relative;
width: 200px;
height: 200px;
margin: auto;
transform-style: preserve-3d;
}
.face {
position: absolute;
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid black;
}
.front {
transform: translateZ(100px);
}
.back {
transform: rotateY(180deg) translateZ(100px);
}
.top {
transform: rotateX(90deg) translateZ(100px);
}
.bottom {
transform: rotateX(-90deg) translateZ(100px);
}
.left {
transform: rotateY(-90deg) translateZ(100px);
}
.right {
transform: rotateY(90deg) translateZ(100px);
}
@keyframes rotate {
from {
transform: rotateY(0deg);
}
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