Multi-Colored text using only CSS

后端 未结 2 531
死守一世寂寞
死守一世寂寞 2021-01-01 04:48

I\'m not sure if my title coherently expressed my issue, but I\'ll explain below.

I would like to assign a different color to each character in a st

2条回答
  •  死守一世寂寞
    2021-01-01 05:13

    This can be achieved with just CSS although only with a few caveats:

    • A monospace font must be used
    • The desired text must be passed through to CSS

    The general principle is:

    • Output the whole word in the desired base colour
    • Use an absolutely positioned pseudo element to output the alternative colour, this is done by specifying the desired letters and using spaces for the letters that are to remain the base colour

    This works because the letters in a monospace font take up the same amount of space (therefore you can be sure the letters will be in the correct position). By using absolute positioning the letters can be laid on top of the word set in HTML.

    .username {
      color: red;
      font-family: monospace;
      position: relative;
    }
    .username:after {
      color: blue;
      content: attr(data-descr);
      left: 0;
      position: absolute;
    }
    username

    JS Fiddle

提交回复
热议问题