Attribute Selectors
What are Attribute Selectors?
Imagine you are sorting a stack of mail. If you want to separate packages from letters, you look at their physical attributes. If you want to find only the packages marked "Fragile", you look for that specific label.In CSS, Attribute Selectors target HTML elements based on the attributes they contain or the exact values of those attributes. They are written inside square brackets [...]:
[required]: Targets any element that has a required attribute.input[type="email"]: Targets only <input> elements that have a type attribute exactly matching "email".Why does it matter?
Attribute selectors are incredibly powerful for styling interactive forms. For example, you can add a red border to text inputs that are[required], or style password inputs differently from standard text inputs. They allow you to apply context-based styling without needing to add extra class names to your HTML.
Syntax Breakdown
[attribute] โ Targets elements containing the specified attribute. E.g., img[alt] targets images with alt descriptions.element[attribute="value"] โ Targets elements with the exact attribute value. E.g., a[target="_blank"] targets links configured to open in new tabs.Common Mistakes
input [type="email"] (with a space) targets elements with type="email" that are *inside* an input element. Keep them connected: input[type="email"].Quick Reference
[attr] โ Targets elements with attribute attr.[attr="val"] โ Targets elements where attr matches val exactly.Your Task
Create an attribute selector in the style block targeting `input` elements with `type="email"` and set their `border-color` to `green`.
index.html
Type code above to start the lesson.
Live Preview