我想要一个文本,在一定点x切换它的颜色.我提供了一个样本,使用文本两次来生成结果,切换为45px.有没有办法这样做在css没有文本两次?也许使用svg?
- div{
- width: 400px;
- height: 40px;
- border: 1px solid #000;
- position: relative;
- }
- div>span{
- position: absolute;
- top: 0;
- left: 0;
- }
- div :nth-child(2){
- color: blue;
- clip: rect(0 200px 40px 45px);
- }
- div :nth-child(1){
- color: red;
- clip: rect(0 45px 40px 0);
- }
- <div>
- <span>Some bicolored Text</span>
- <span>Some bicolored Text</span>
- </div>
解决方法
另一个可能的选择是使用SVG.您可以使用梯度在SVG中创建多色文本.如果两个相邻的梯度停止位置在相同的位置,那么您将得到颜色之间的一个明显的过渡.如果两个相邻的梯度停止位置在不同的位置,那么您将获得颜色之间的平滑过渡.你可以拥有你想要的色块.例如…
- <svg width="200" height="80" xmlns="http://www.w3.org/2000/svg">
- <defs>
- <linearGradient id="bicolored">
- <stop offset="33%" stop-color="red"/>
- <stop offset="33%" stop-color="blue"/>
- </linearGradient>
- <linearGradient id="tricolored">
- <stop offset="33%" stop-color="red"/>
- <stop offset="33%" stop-color="green"/>
- <stop offset="66%" stop-color="green"/>
- <stop offset="66%" stop-color="blue"/>
- </linearGradient>
- <linearGradient id="smooth">
- <stop offset="33%" stop-color="red"/>
- <stop offset="66%" stop-color="blue"/>
- </linearGradient>
- </defs>
- <text x="0" y="20" fill="url(#bicolored)">Some bicolored Text</text>
- <text x="0" y="40" fill="url(#tricolored)">Some tricolored Text</text>
- <text x="0" y="60" fill="url(#smooth)">Some smooth gradient Text</text>
- </svg>
注意,在SVG中,颜色停止在相对位置(例如0到1,0%到100%).如果您尝试将颜色停留在特定的像素位置,这可能会使其有点困难.
请注意,您必须手动将文本元素放置在svg元素中.