2

I want to pass CSS ::after content as a specific word from its class element.

If class names are "language-css", "language-html", etc, in this case, I want to pass the content as the word after the "-".

code::before {
  content: attr(class);
}
<code class="language-css"> some code here </code>
<code class="language-html"> some code here </code>
<code class="language-javascript"> some code here </code>

I know this returns the whole text from the CSS class, does CSS support any split function as JavaScript does?

5
  • 7
    No, CSS does not support this. Put the text you want in a data-attribute and use this instead. Commented Nov 25, 2021 at 12:32
  • 1
    alternativly you could also just declare the text in CSS directly like: code.language-css::before { content: "CSS"; } Commented Nov 25, 2021 at 12:33
  • the element and class name generated by a third-party plugin, so can we work unless script. Commented Nov 25, 2021 at 12:35
  • @tacoshy using code.language-css::after is very hard, because there're lot of languages in the loop. Commented Nov 25, 2021 at 12:36
  • while generating your class name, you can also generate a data-attribute striped of language- and instead using the class for the pseudo content, use the data-attribute . It could be: data-langage="html" Commented Nov 25, 2021 at 12:51

1 Answer 1

3

In this particular case, you can hack is with some negative text-indent if the prefix is always the same. The code element is using a monospace font so it's easy using ch unit

code::before {
  content: attr(class);
  display:inline-block;
  text-indent:-9ch; /* adjust this based on your real case */
  clip-path:inset(0); /* hide the overflow */
}
<code class="language-css"> some code here </code>
<code class="language-html"> some code here </code>
<code class="language-javascript"> some code here </code>

Sign up to request clarification or add additional context in comments.

3 Comments

That's a really nice solution, this will work in this case since it will be only 1 line. This won't work with multi-line text (just as an info for everyone else stumbling on this great solution)
@cloned it does work with multi-line text, reduce your screen width and the text will wrap naturally
You are right, it really works with multiline text. Thought it will cut 10 characters off from each line. I stand corrected, thanks for the clarification. Nice solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.