csshtmlpseudo-elementcss-content

Use content of an element in attr() of pseudo-element


I have the following text:

<span class="page-number">42</span>

And I want to create a pseudo-element with something like this:

span.page-number::after {
    content: attr(text());
}

Such that the content of the pseudo-element is the text of the element, in this case 42. Can I do something like that through some trickery?


Solution

  • Use data-* attribute (i.e: data-number) and the CSS attr() getter function inside a ::before or ::after pseudo element:

    span::after {
      content: attr(data-number);
    }
    <span class="page-number" data-number="Item No.42">42</span>