使用Unicode符号可实现静态评分展示,通过HTML与CSS结合创建可交互星级评分,利用伪元素和渐变背景支持半星效果,满足不同场景需求。

在CSS中制作评分星星组件,可以通过字体图标、Unicode符号或背景图片实现。最常见且简单的方式是使用Unicode星星符号配合HTML与CSS结合,支持点击评分和显示半星效果。
使用Unicode星星创建静态评分
通过Unicode字符(★ 和 ☆)表示实心和空心星星,适合展示固定评分。
示例代码: ```html ```.rating {
font-size: 24px;
color: #ffcc00;
letter-spacing: 2px;
}这种方式简单直接,适用于只读评分展示。
实现可交互的点击评分
利用隐藏的单选按钮(radio)和CSS样式模拟可点击的星星评分。
立即学习“前端免费学习笔记(深入)”;
.star-rating {
display: flex;
direction: row-reverse;
gap: 2px;
font-size: 30px;
margin: 10px 0;
}
.star-rating input {
display: none;
}
.star-rating label {
color: #ddd;
cursor: pointer;
transition: color 0.2s;
}
.star-rating label:hover,
.star-rating label:hover ~ label {
color: #ffcc00;
}
.star-rating input:checked ~ label {
color: #ffcc00;
}说明:将radio按钮反向排列,方便使用~选择器控制后续标签变色。鼠标悬停时高亮从当前星到末尾的所有星。
支持半星和更精细的评分显示
使用伪元素和宽度控制实现半星效果,适合用于展示如3.5星这样的评分。
.rating-bar {
--rating: 0;
width: 100px;
height: 20px;
background: linear-gradient(to right,
#ffcc00 calc(var(--rating) * 20%),
#ddd calc(var(--rating) * 20%));
border-radius: 4px;
position: relative;
background-image: repeating-linear-gradient(
to right,
transparent,
transparent 19px,
#ccc 19px,
#ccc 20px
);
background-size: 20px 20px;
}
.rating-bar::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: calc(var(--rating) * 20px);
height: 100%;
background: #ffcc00;
mask: repeating-linear-gradient(
to right,
transparent,
transparent 10px,
black 10px,
black 20px
);
-webkit-mask: repeating-linear-gradient(
to right,
transparent,
transparent 10px,
black 10px,
black 20px
);
}此方法用渐变背景模拟填充,结合mask实现半星锯齿效果,适合高精度评分展示。
基本上就这些。根据需求选择只读、交互或半星方案,灵活搭配即可。










