css骰子制作
使用CSS制作骰子
骰子可以通过CSS的伪元素、变换和动画效果来实现。以下是一个简单的3D骰子实现方法。
HTML结构
<div class="dice">
<div class="face front">1</div>
<div class="face back">6</div>
<div class="face right">4</div>
<div class="face left">3</div>
<div class="face top">2</div>
<div class="face bottom">5</div>
</div>
CSS样式
.dice {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
animation: rotate 5s infinite linear;
}
.face {
position: absolute;
width: 100%;
height: 100%;
background: white;
border: 2px solid black;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
}
.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 {
from { transform: rotateX(0deg) rotateY(0deg); }
to { transform: rotateX(360deg) rotateY(360deg); }
}
制作2D骰子动画
如果需要更简单的2D骰子动画效果,可以使用CSS变换和关键帧动画。
HTML结构
<div class="dice-2d">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
CSS样式
.dice-2d {
width: 100px;
height: 100px;
background: white;
border: 2px solid black;
border-radius: 10px;
position: relative;
animation: shake 0.5s infinite;
}
.dot {
width: 20px;
height: 20px;
background: black;
border-radius: 50%;
position: absolute;
}
/* 调整点位置模拟骰子点数 */
.dot:nth-child(1) { top: 15px; left: 15px; }
.dot:nth-child(2) { top: 15px; right: 15px; }
.dot:nth-child(3) { top: 40px; left: 40px; }
.dot:nth-child(4) { bottom: 15px; left: 15px; }
.dot:nth-child(5) { bottom: 15px; right: 15px; }
.dot:nth-child(6) { bottom: 40px; right: 40px; }
@keyframes shake {
0% { transform: rotate(0deg); }
25% { transform: rotate(5deg); }
50% { transform: rotate(0deg); }
75% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
响应式骰子设计
为了使骰子在不同设备上都能正常显示,可以添加媒体查询调整大小。
@media (max-width: 600px) {
.dice, .dice-2d {
width: 60px;
height: 60px;
}
.face {
font-size: 16px;
}
.dot {
width: 12px;
height: 12px;
}
}
这些方法提供了从简单到复杂的骰子实现方案,可以根据项目需求选择适合的方式。3D效果需要浏览器支持CSS 3D变换,而2D方案兼容性更好。







