CSS attribute presence and value selectors

CSS attribute selector can be used to select DOM elements based on attribute presence of their values. We can use attribute selectors in multiple ways. These are some commonly used ways.

[attribute] element has attribute
[attribute=value] element has attribute=value
[attribute~=value] element attribute contains word value (words should be whitespace separated)
[attribute|=value] element attribute either equals value or begins with value and ten followed by –

Some examples for attribute selectors:

Attribute selector presence example

Change color of disabled buttons (#form1 input[disabled])

<style type="text/css">
  #form1 input[disabled] {color:lightgray;}
</style>

<form id="form1">
<input type="text" value="textval" />
<input type="button" value="button1" disabled />
<input type="button" value="button2" />
</form>
refresh

Attribute selector [attribute=value] example

Change color of input type=button (#form1 input[type=button])

<style type="text/css">
  #form1 input[type=button] {background-color:lightgreen;}
</style>

<form id="form1">
<input type="text" value="textval" />
<input type="button" value="button1" />
<input type="button" value="button2" />
</form>
refresh

Multiple attribute selector example

Change color of input type=button when value=green (#form1 input[type=button][value=green])

<style type="text/css">
  #form1 input[type=button][value=green] {background-color:green;}
</style>

<form id="form1">
<input type="text" value="textval" />
<input type="button" value="button1" />
<input type="button" value="green" />
</form>
refresh

Related

Specification

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments