Targeting Elements: CSS Attribute Selectors
Go beyond classes and IDs. Learn to style elements based on their attributes for cleaner and more powerful CSS.
Welcome! Let's explore CSS attribute selectors. They let us style elements based on their HTML attributes.
/* Let's begin! */
Complete Guide to Attribute Selectors
Attribute selectors are your secret weapon for cleaner, more semantic CSS. Here is a complete reference of all available operators with live examples.
Selector | Description | Live Demo |
---|---|---|
[target] | Presence Selects elements that have the specified attribute, regardless of its value. | |
[type="password"] | Exact Value Selects elements where the attribute has an exact value. | |
[class~="btn-primary"] | Word Contains Selects elements where the attribute value is a space-separated list containing a specific word. | |
[lang|="en"] | Starts With (Hyphen) Selects elements where the attribute value is exactly the given string or starts with it followed by a hyphen. | This text is in English. |
[href^="https"] | Starts With (Substring) Selects elements where the attribute value starts with the specified string. | |
[href$=".pdf"] | Ends With (Substring) Selects elements where the attribute value ends with the specified string. | |
[alt*="dog"] | Contains (Substring) Selects elements where the attribute value contains the specified substring anywhere. | |
[type="TEXT" i] | Case-Insensitive Adds the `i` flag before the closing bracket `]` to make the value matching case-insensitive. |
Practice Zone
Interactive Test 1: Drag & Drop
Assemble the CSS selector to target an anchor tag <a>
that has a `target` attribute with the exact value of `_blank`.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Fill in the Blanks
Complete the selector to style `input` fields that are required.
Rellena los huecos en cada casilla.
input[] { border-color: red; }
Practice Example: Code Editor
Write a CSS rule to select all links whose href
attribute ends with .pdf
and give them a green background color.
Box-Sizing Property
Property | Description |
---|---|
box-sizing: content-box; | The element's size excludes padding and border (default value). |
box-sizing: border-box; | The element's size includes padding and border. |
* Write your CSS code and apply it to see how `box-sizing` affects the size of the elements.