css制作骰子
CSS 制作骰子的方法
使用 CSS 可以创建各种样式的骰子,以下是几种常见的实现方式:
基础骰子结构
HTML 结构通常由一个容器和多个点(dots)组成:
<div class="dice">
<div class="dot"></div>
<!-- 更多点根据骰子面数添加 -->
</div>
CSS 基础样式:
.dice {
width: 100px;
height: 100px;
background-color: white;
border: 2px solid black;
border-radius: 10px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.dot {
width: 20px;
height: 20px;
background-color: black;
border-radius: 50%;
}
不同点数的骰子面
-
1 点骰子:
.dice.one { justify-content: center; align-items: center; } -
2 点骰子:

.dice.two { justify-content: space-between; } .dice.two .dot:nth-child(1) { align-self: flex-start; } .dice.two .dot:nth-child(2) { align-self: flex-end; } -
3 点骰子:
.dice.three { justify-content: space-between; } .dice.three .dot:nth-child(1) { align-self: flex-start; } .dice.three .dot:nth-child(2) { align-self: center; } .dice.three .dot:nth-child(3) { align-self: flex-end; } -
4 点骰子:
.dice.four { flex-wrap: wrap; justify-content: space-between; align-content: space-between; } .dice.four .dot { width: 40%; height: 40%; }
3D 骰子效果
使用 CSS 3D 变换创建更真实的骰子:

.dice-3d {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
transform: rotateX(45deg) rotateY(45deg);
animation: spin 5s infinite linear;
}
@keyframes spin {
from { transform: rotateX(0) rotateY(0); }
to { transform: rotateX(360deg) rotateY(360deg); }
}
响应式骰子
使用 CSS 变量使骰子大小可调整:
.dice {
--dice-size: 100px;
--dot-size: calc(var(--dice-size) * 0.2);
width: var(--dice-size);
height: var(--dice-size);
}
.dot {
width: var(--dot-size);
height: var(--dot-size);
}
高级技巧
-
伪元素创建点: 可以使用 ::before 和 ::after 伪元素减少 HTML 标记:
.dice.two::before, .dice.two::after { content: ''; width: 20px; height: 20px; background-color: black; border-radius: 50%; } -
CSS Grid 布局: 对于更复杂的排列,可以使用 CSS Grid:
.dice.four { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; }
这些方法可以组合使用,根据需求创建各种样式的骰子效果。






