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>
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>
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>
Related
- CSS type selectors - define style by element name
- CSS universal selector
- CSS attribute substring selectors
- CSS class selectors - define style by class name
- CSS - style for element having two classes (both)
- CSS id selectors - define style by element id