两种颜色的文字 [英] Text with two colors

查看:61
本文介绍了两种颜色的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个文本,该文本会在某个点x处切换其颜色.我提供了一个示例,该示例使用文本两次来产生结果,并且开关位于45px.有没有办法在CSS中执行此操作而无需两次输入文本?也许使用svg?

I would like to have a text that switches its color at a certain point x. I have provided a sample that uses the text twice to produce the result, with the switch at 45px. Is there a way to do this in css without having the text twice? Maybe using 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中创建多色文本.如果两个相邻的渐变色标位于相同的位置,那么您将在颜色之间获得清晰的过渡.如果两个相邻的渐变色标位于不同的位置,那么您将获得颜色之间的平滑过渡.您可以根据需要设置任意多个色标.例如...

Another possible option is to use SVG. You can create multi colored text in SVG using gradients. If two adjacent gradient stops are at the same position then you will get a sharp transition between colors. If two adjacent gradient stops are at different positions then you will get a smooth transition between colors. You can have as many color stops as you want. For example...

<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%).如果您尝试将色标停在特定的像素位置,则可能会有点困难.

Note that in SVG, the color stops are at relative positions (e.g. 0 to 1, 0% to 100%). This could make it a little hard if you are trying to place the color stops at specific pixel locations.

请注意,在SVG中,您必须手动将文本元素放置在svg元素内.

Note that in SVG, you have to manually position the text element within the svg element.

这篇关于两种颜色的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆