My goal is to: check if the title attribute is not empty; if it is not then there should be added the value of this title attribute plus a hyphen. On the other hand, if the title attribute is empty then the " - " should not be added at all.
Here is my current CSS code:
div:hover::before{content:attr(title):not(attr(title)="") " - ";}
but it doesn’t work as expected.
For example:
<div title="My username">some text</div>
should display the following on hover:
My username - some text
But if:
<div title="">some text</div>
or (no title on div):
<div>some text</div>
then the display on hover should be:
some text
Is it possible to fix it?
You can use attribute selectors in conjunction with the attr()
function to accomplish this. The attr()
function simply grabs the value of a given attribute — it does not support any conditional statements itself.
Notice that I use [title=""]
and :not([title])
to account for both empty title attributes as well as the lack of a title attribute altogether. You could omit the :not()
part by including [title]
in your first rule instead, but that doesn't work in Internet E— sorry, I meant it doesn't work in Chrome.
div:hover::before {
content: attr(title) " - ";
}
div[title=""]:hover::before, div:not([title]):hover::before {
content: none;
}
<div title="My username">some text</div>
<div title="">some text</div>
<div>some text</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With