CSS Attribute Selector: Apply class if custom attr

2019-01-28 00:07发布

问题:

I'd like to use CSS Attribute Selector to apply a class to some spans, but only if they have content. I have a custom attribute that will only have a value if the span has content: "entityvalue". When using the CSS below, it does not apply the class to any elements, even if entityvalue='1634' is in the HTML.

.ApplicationName[entityvalue="*"]  {
                 display: inline;
                 background-image: url("../images/icon_application.PNG");
                 background-repeat: no-repeat;
                 background-position: left;
                 padding-left: 12px;
                 }

I tried .ApplicationName[entityvalue!=""] as found on some sites but apparently it's not in the CSS standards (doesn't work in Chrome) which really sucks, because .ApplicationName[entityvalue=""] does exactly the opposite of what I need...

Here are examples of a span/div WITH content (that should be styled) and a span/div WITHOUT content (which should NOT be styled):

<div class="ApplicationName Redirect" entitytype="Application" entityvalue=""></div>

<div class="ApplicationName Redirect" entitytype="Application" entityvalue="1234">Microsoft Outlook</div>

回答1:

Omit the value part:

.ApplicationName[entityvalue]

This works with IE7+.

If you're paranoid about entityvalue being set to emptiness, and you don't want to include those elements:

.ApplicationName[entityvalue]:not([entityvalue=""])

This does not work with IE7+.

If you do need to cater to that, well, you have some options:

  • Define an override/reset style for .ApplicationName[entityvalue=""], so you have one rule with the first selector above, and another rule with this one.

  • Use JavaScript to look for elements with the empty attribute and add a class which you can style.

  • If you can modify server-side code to output that attribute differently, that's an even easier route to take.