Attribute Selectors
CSS attribute selectors allow you to style elements based on their attributes and values, providing greater flexibility in targeting elements.
Selector | Example | Description |
---|---|---|
[attribute] | input[disabled] | Selects elements with a specified attribute |
[attribute=value] | input[type="text"] | Selects elements with an exact attribute value |
[attribute~=value] | div[class~="box"] | Selects elements with an attribute containing a word (space-separated list) |
[attribute^=value] | a[href^="https"] | Selects elements where the attribute starts with a specific value |
[attribute$=value] | img[src$=".jpg"] | Selects elements where the attribute ends with a specific value |
[attribute*=value] | a[href*="google"] | Selects elements where the attribute contains a specific value |
Explanation of Selectors
Selector | Description | Example Usage |
[attribute] | Targets elements that have a specific attribute | input[required] { border: red; } |
[attribute=value] | Matches exact value | input[type="checkbox"] { width: 20px; } |
[attribute~=value] | Matches a word in a space-separated list | div[class~="featured"] { background: yellow; } |
[attribute^=value] | Matches attributes that start with a value | a[href^="https"] { color: green; } |
[attribute$=value] | Matches attributes that end with a value | img[src$=".png"] { border-radius: 10px; } |
[attribute*=value] | Matches attributes containing a value | a[href*="facebook"] { font-weight: bold; } |
Example:
/* Select all input fields with type text */
input[type="text"] {
border: 2px solid blue;
}
/* Highlight all links that start with "https" */
a[href^="https"] {
color: green;
}
/* Add a red border to images ending with .jpg */
img[src$=".jpg"] {
border: 3px solid red;
}
✔ Ensures specific styling for different attributes
✔ Improves precision when styling elements dynamically
Qus. 1 : Which of the following selector selects all elements of E that have the attribute attr that end with the given value?
- E[attr^=value]
- E[attr$=value]
- E[attr*=value]
- None of these
- E ~ F
- ::after
- :checked
- None of these
- [attr]
- [attr=""]
- [attr=*]
- attr[ ]
- A → 2, B → 5, C → 3, D → 4
- A → 2, B → 6, C → 3, D → 4
- A → 5, B → 1, C → 3, D → 4
- A → 2, B → 1, C → 3, D → 4