CSS allows to select HTML elements that have specific attributes or attribute values. Element can be selected in number of ways. Some examples are given below:
- [attribute]: It selects the element with specified attribute.
- [attribute=”value”]: It selects the elements with a specified attribute and value.
- [attribute~=”value”]: It selects the elements with an attribute value which contains a specified word.
- [attribute|=”value”]: It selects the elements with the specified attribute which starts with the specified value.
- [attribute^=”value”]: It selects the elements in which attribute value begins with a specified value.
- [attribute$=”value”]: It selects the elements in which attribute value ends with a specified value.
- [attribute*=”value”]: It selects the elements in which attribute value contains a specified value.
Example 1: This example changes the background-color of <a> element by selecting the element [target] using CSS.
<!DOCTYPE html> < html > < head > < title > Attribute selector in CSS </ title > < style > a[target] { background-color: yellow; } a { font-size: 20px; } </ style > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > geeksforgeeks.org </ a > < br >< br > google.com </ a > </ body > </ html > |
Output:
Example 2: This example changes the background-color and text-color of the <a> element by selecting element having [target = “_top”] using CSS.
<!DOCTYPE html> < html > < head > < title > Attribute selector in CSS </ title > < style > a[target=_top] { background-color: green; color: white; } a { font-size: 20px; } </ style > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > geeksforgeeks.org </ a > < br >< br > google.com </ a > </ body > </ html > |
Output:
Example 3: This example changes the background-color and text-color of the <p> element by selecting element having [class^=”top”] using CSS.
<!DOCTYPE html> < html > < head > < title > Attribute selector in CSS </ title > < style > [class^="top"] { background-color: green; color: white; } p { font-size: 20px; } </ style > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p class = "top-p" >A computer science portal</ p > < p class = "topPara" >Attribute Selector Example</ p > < p class = "Para" >CSS does not applies here</ p > </ body > </ html > |
Output:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.