CSS渐变填充text in:before在单独的行上



我试图使用CSS创建一个"五星评级",但需要在文本之前的行上的星星。我的出发点是CSS技巧五星评级五种方法中的最后一种。基本上,它分配一个评级数字作为CSS变量,然后使用它来计算星号上的渐变填充,这些星号是:before标记中的unicode字符。

问题是,我需要星号与正文分开行。

他将整个div设置为display: inline-block:

:root {
--star-color: #fff;
--star-background: #fc0;
}
.Stars {
--percent: calc(var(--rating) / 5 * 100%);

display: inline-block;
line-height: 1;

&::before {
content: '★★★★★';
letter-spacing: 3px;
background: linear-gradient(90deg, 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.3;"></div>

各种各样的东西,我试着让星星在自己的线上:

  • :before更改为display: block
  • :before更改为display: block; background-size: 100%
  • <div>更改为display: flex; flex-direction: column
  • 添加'A'转义字符到:beforecontent

以上所有的结果都以各种不同的方式导致背景与星形文字不对齐,最有趣的是当文本居中时,这是我的实际用例。

关于如何实现这一点有什么想法吗?

片段:

:root {
--star-color: #fff;
--star-background: #fc0;
}
.Stars {
--percent: calc(var(--rating) / 5 * 100%);

display: inline-block;
line-height: 1;
width: 100%;
}
.Stars:before {
content: '★★★★★';

letter-spacing: 3px;
background: linear-gradient(90deg, var(--star-background) var(--percent), var(--star-color) var(--percent));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.centered {
text-align: center;
}
.two-line:before {
display: block;
}
<h1>Working</h1>
<div class="Stars" style="--rating: 4;">4 stars!</div>
<div class="Stars" style="--rating: 2.5;">2.5 stars. Meh.</div>
<div class="Stars" style="--rating: 1.5;">1.5 stars. Doh!</div>
<div class="Stars centered" style="--rating: 4;">4 stars!</div>
<div class="Stars centered" style="--rating: 2.5;">2.5 stars. Meh.</div>
<div class="Stars centered" style="--rating: 1.5;">1.5 stars. Doh!</div>
<h1>Not Working</h1>
<div class="Stars two-line" style="--rating: 4;">4 stars!</div>
<div class="Stars two-line" style="--rating: 2.5;">2.5 stars. Meh.</div>
<div class="Stars two-line" style="--rating: 1.5;">1.5 stars. Doh!</div>
<div class="Stars centered two-line" style="--rating: 4;">4 stars!</div>
<div class="Stars centered two-line" style="--rating: 2.5;">2.5 stars. Meh.</div>
<div class="Stars centered two-line" style="--rating: 1.5;">1.5 stars. Doh!</div>

更新这个样式!

.two-line:before {
display: inline-block;
}

最新更新