Search code examples
htmlcssgoogle-chromeword-spacing

underline a paragraph having word-spacing set


When using word-spacing in an underlined element, if the element contains spans, spaces are not correctly underlined making it really ugly...

Is there a work around for that?

p {
  text-decoration: underline;
  word-spacing: 1em;
}
<p>
  <span>test</span> <span>test</span>
</p>
<p>
  test test
</p>

Edit:

I found this trick that is almost satisfying for my use case:

p {
  text-decoration-line: underline;
}
span:after {
  content: ' ';
  letter-spacing: 1em;
}
<p>
  <span>test</span>
  <span>test</span>
</p>

The issue is that I would like to use it with a Zero-width space, like \u200B, but for some reason, it doesn't work. Maybe I'm doing it wrong...

p {
  text-decoration-line: underline;
}
span:after {
  content: '\200B';
  letter-spacing: 1em;
}
<p>
  <span>test</span>
  <span>test</span>
</p>


Solution

  • A workaround is to remove the white space between the spans and use a hack with pseudo element to simulate word-spacing. It works but it remain a hacky solution:

    p {
      text-decoration: underline;
      word-spacing: 1em;
      display:flex; /*remove white space*/
    }
    
    span:not(:last-child)::after {
      content:"\00a0";
    }
    <p>
      <span>test</span> <span>test</span>
    </p>
    <p>
      test test
    </p>

    If you will only have spans you can do it like this:

    p {
      text-decoration: underline;
    }
    
    span:not(:last-child)::after {
      content:" ";
      letter-spacing: 1em;
    }
    <p>
      <span>test</span> <span>test</span>
    </p>