csscss-selectorspseudo-element

What’s the point of the ::before and ::after pseudo-element selectors in CSS?


I have used CSS pseudo-element selectors like many others, mainly just to say I've used them.

But I am racking my brain and struggling to come up with a reason for their place alongside markup.

Take the following example:

p::after {
  content: "*";
}
<p>Hello</p>

What is the advantage of using this over using <span> tags?

Am I missing the point of ::before and ::after? Is there some rock solid reason for using them over pre-existing semantic markup?


Solution

  • The CSS2.1 spec says this about generated content:

    In some cases, authors may want user agents to render content that does not come from the document tree. One familiar example of this is a numbered list; the author does not want to list the numbers explicitly, he or she wants the user agent to generate them automatically. Similarly, authors may want the user agent to insert the word "Figure" before the caption of a figure, or "Chapter 7" before the seventh chapter title. For audio or braille in particular, user agents should be able to insert these strings.

    Basically the purpose is to minimize pollution of the content structure by "content" that is otherwise more suited as presentational elements, or better to be automated.