About this Post

Attribute selectors match HTML elements based on their presence or value.


Let's chat about selectors, namely, the CSS attribute selector. The CSS attribute selector matches any element(s) based on their attributes. Syntax wise, an attribute selector uses square brackets [] to select elements based on the presence or value of attributes.

First off, let's review what a CSS selector is. A CSS selector is a pattern that matches elements in the Docuemnt Object Model (DOM). The CSS selector is used to select the element(s) you want to style.

Typically, you might use a CSS selector to select an element by its type, class, or id. For example, the following CSS selector selects all <img> elements on the page and sets their width to 100%.

img { width: 100%; }

Now, let's use the attribute selector to select <img> elements based on their attributes. The following CSS selector selects all <img> elements that have a src attribute (regardless of the value), and sets their width to 100%.

img[src] { width: 100%; }

Next, let's use the attribute selector to select <img> elements based on their src attribute value. The following CSS selector selects all <img> elements that have a src attribute with a value of https://example.com, and sets their width to 100%.

img[src="https://example.com"] { width: 100%; }

This is just the tip of the iceberg when it comes to using the attribute selector. To learn more, check out the MDN documentation.