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

在CSS中制作评分星星组件,可以通过字体图标、Unicode符号或背景图片实现。最常见且简单的方式是使用Unicode星星符号配合HTML与CSS结合,支持点击评分和显示半星效果。
通过Unicode字符(★ 和 ☆)表示实心和空心星星,适合展示固定评分。
示例代码: ```html ```.rating {
font-size: 24px;
color: #ffcc00;
letter-spacing: 2px;
}这种方式简单直接,适用于只读评分展示。
利用隐藏的单选按钮(radio)和CSS样式模拟可点击的星星评分。
立即学习“前端免费学习笔记(深入)”;
<div class="star-rating"> <input type="radio" name="rating" id="star1" value="1"> <label for="star1">★</label> <input type="radio" name="rating" id="star2" value="2"> <label for="star2">★</label> <input type="radio" name="rating" id="star3" value="3"> <label for="star3">★</label> <input type="radio" name="rating" id="star4" value="4"> <label for="star4">★</label> <input type="radio" name="rating" id="star5" value="5"> <label for="star5">★</label> </div>
.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星这样的评分。
<div class="rating-bar" style="--rating: 3.7"></div>
.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实现半星锯齿效果,适合高精度评分展示。
基本上就这些。根据需求选择只读、交互或半星方案,灵活搭配即可。
以上就是在css中如何制作评分星星组件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号