Check CSS header attribute if not empty and add content

My goal: to check if the title attribute is not empty; if it is not, then the value of this attribute title plus a hyphen should be added. On the other hand, if the title attribute is empty, then "-" should not be added at all.

Here is my current CSS code:

div:hover::before{content:attr(title):not(attr(title)="") " - ";} 

but it does not work properly.

For instance:

 <div title="My username">some text</div> 

The following should be displayed:

My username is text

But if:

 <div title="">some text</div> 

or (no name in the div):

 <div>some text</div> 

then the hover display should be:

some text

Can this be fixed?

+5
source share
1 answer

You can use the attribute selector in conjunction with the attr() function to accomplish this. The attr() function simply captures the value of this attribute - it does not support any conditional statements.

Please note that I use [title=""] and :not([title]) to account for both empty title attributes and the absence of the title attribute. You can omit the :not() by including [title] in your first rule, but this does not work on the Internet. Sorry, I meant that this does not 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> 
+5
source

Source: https://habr.com/ru/post/1208628/


All Articles