You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现在CSS绘制的星形形状内部写入数字文本内容

实现方案

你的代码中数字和星星默认行内并排显示,所以数字出现在侧边。只需要调整CSS让星星作为底层背景,数字层叠在星星上方即可,修改后的代码如下:

调整后的CSS代码

.Stars {
  --percent: calc(var(--rating) / 5 * 100%);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  position: relative;
  font-family: Times;
  line-height: 1;
  margin-left: 500px;
  /* 数字样式可自行调整 */
  color: #000;
  font-size: calc(var(--star-size) * 0.3);
  font-weight: bold;
}
.Stars::before {
  content: '★';
  position: absolute;
  inset: 0;
  z-index: -1;
  font-size: var(--star-size);
  background: linear-gradient(0deg, var(--star-background) var(--percent), var(--star-color) var(--percent));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

HTML代码无需修改

<div class="Stars" style="--rating: 2.5;--star-size: 60px;
  --star-color: #fff;--star-background: #fc0; text-align: center;" aria-label="Rating of this product is 2.3 out of 5.">3
</div>

可调整项

  • 可修改.Stars的color属性调整数字颜色,若星星填充色较深,可改为白色#fff提升对比度
  • 可修改font-size: calc(var(--star-size) * 0.3)中的系数调整数字大小

内容的提问来源于stack exchange,提问作者Muneeba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 03:15:02