Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I target elements with an attribute that has any value in CSS?

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.

like image 957
Marty Avatar asked Feb 14 '12 03:02

Marty


People also ask

What CSS selector is used to select elements with a specified attribute and value?

The [attribute=value] selector is used to select elements with the specified attribute and value.

Can we use contains in CSS selector?

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).

How do I style a data attribute in CSS?

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.

Which is the correct css3 code to select the HTML element based on their attribute value?

[attribute^=”value”] Selector: This selector is used to select all the elements whose attribute value begins with the specified value.


1 Answers

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

like image 157
Alex Avatar answered Oct 15 '22 00:10

Alex