Eliminate element's trailing space between last word and ::after text content

Viewed 51

Is there a way to specify in the CSS that there should be no space between an HTML element's contents and its ::after contents? Obviously I could ask that authors not include a space in the HTML, but I can't rely on the HTML authors to do this consistently. Here's what I'm talking about:

.x::after {
  content: "\00A7";
}
<span class="x">I wish these were identical </span>
<br>
<span class="x">I wish these were identical</span>

2 Answers

You can achieve visually uniform outcome if you prepend extra space to generated content ::after (what is probably a good thing in general, because otherwise it might be interpreted as part of the last word by screen readers) and offset it by its width. Adjacent white space inside normal text flow automatically collapses to single space, so any amount of spaces should produce same outcome, regardless if it originated from the text content or CSS pseudo element (again, provided it is in normal "inline" flow with white-space: normal):

.x::after {
  content: " \00A7";
  margin-left: -.5ch;
}
<span class="x">I wish these were identical </span>
<br>
<span class="x">I wish these were identical</span>

You could use flex:

HTML

<span class="x">I wish these were identical </span>
<br>
<span class="x">I wish these were identical</span>

CSS

.x::after{content:"\00A7"}
span{display: flex;}

DEMO HERE

Related