Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking CSS title attribute if it's not empty and add content

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?

like image 704
NonCoder Avatar asked Dec 09 '14 05:12

NonCoder


1 Answers

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>
like image 90
BoltClock Avatar answered Oct 03 '22 10:10

BoltClock