How do you set styles by attributes?
Styles by attribute are set using attribute selectors, they let you select elements based on the presence of an attribute or its value. The syntax involves square brackets [].
1. By the presence of an attribute
css
[input] {
background: yellow;
}The selector applies to all elements that have the input attribute.
2. By exact value match
css
input[type="text"] {
border: 1px solid black;
}The selector will select <input type="text">.
3. By the start of the value (^=)
css
a[href^="https"] {
color: green;
}Selects links whose href starts with https.
4. By the end of the value ($=)
css
a[href$=".pdf"] {
color: red;
}Selects all links leading to a PDF.
5. By a substring within the value (*=)
css
a[href*="google"] {
color: blue;
}Selects links whose address contains the word google.
Summary
Attribute selectors let you select elements not by class or tag, but by the data contained in the attributes themselves. This is useful for:
- styling forms
- styling links by type
- targeting elements with custom attributes (
data-*) - more flexible selection of DOM nodes without extra classes
They make CSS more precise and flexible in controlling styles.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.