I know that I can target elements which have a specific attribute in CSS, for example:
input[type=text] { font-family: Consolas; }
But is it possible to target elements which have an attribute of any value (except nothing i.e. when the attribute hasn't been added to the element)?
Roughly something like:
a[rel=*] { color: red; }
Which should target the first and third <a>
tags in this HTML:
<a href="#" rel="eg">red text</a> <a href="#">standard text</a> <a href="#" rel="more">red text again</a>
I figure it's possible because by default, cursor: pointer
seems to be applied to any <a>
tag which has a value for its href
attribute.
The [attribute=value] selector is used to select elements with the specified attribute and value.
A custom built CSS selector for more advanced users can be built using the "contains" selector. The "contains" selector is useful in cases where we are looking for an element that "contains" some text (case sensitive).
To use this selector, add a pipe character (|) before the equals sign. For example, li[data-years|="1900"] will select list items with a data-years value of “1900-2000”, but not the list item with a data-years value of “1800-1900”. Value ends with: attribute value ends with the selected term.
[attribute^=”value”] Selector: This selector is used to select all the elements whose attribute value begins with the specified value.
The following will match any anchor tag with a rel
attribute defined:
a[rel] { color: red; }
http://www.w3.org/TR/CSS2/selector.html#pattern-matching
Update: To account for the scenario @vsync mentioned, in the comment section (differentiating between emtpy/non-empty values), you could incorporate the CSS :not
pseudo-class:
a[rel]:not([rel=""]) { color: red; }
https://developer.mozilla.org/en-US/docs/Web/CSS/:not
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