Home > front end >  How do I center a letter on its background-color when using the letter-spacing property?
How do I center a letter on its background-color when using the letter-spacing property?

Time:02-17

I'm trying to highlight every letter of a word a different color by using the background-color property, but I want to separate the letters to give them a blocky look. The problem is that when I increase the letter-spacing, the highlighted parts are lopsided, not centered around the letter like I want them. Here's an extreme example:

<mark style="background-color: red">t</mark><mark style="background-color: green">e</mark<mark style="background-color: blue">s</mark><mark style="background-color: yellow">t</mark>
mark
{
   color: white;
   letter-spacing: 1em;
}

The background extends farther to the right of the letter than the left. Is there any way to center the letter in the background, so that it's highlighted evenly on both sides? Currently I'm using &nbsps around each letter and avoiding using letter-spacing altogether, which works fine, but a solution that doesn't require the addition of any characters would be much nicer. What I'm currently using:

<mark style="background-color: red">&nbspt&nbsp</mark><mark style="background-color: green">&nbspe&nbsp</mark<mark style="background-color: blue">&nbsps&nbsp</mark><mark style="background-color: yellow">&nbspt&nbsp</mark>

CodePudding user response:

If they're already in separate elements, you could just use padding.

mark
{
   color: white;
   padding: 0 1em;
}
<mark style="background-color: red">t</mark><mark style="background-color: green">e</mark><mark style="background-color: blue">s</mark><mark style="background-color: yellow">t</mark>

  • Related