How-To: CSS Attribute selectors

Target HTML elements based on a specific attribute, (not only class or id). The examples below use the Title attribute but the same can be used for any HTML attribute.

Attribute (Match all occurences of the attribute)

Style any elements that have a Title attribute
[title] { color: orange; }

Attribute=Value (Exact match)

Style any elements that have a Title attribute = "Home Page"
[title="Home Page"] { color: orange; }

Style any elements that have an HREF attribute = "Emw3.com"
a[href="https://emw3.com"] { color: orange; }

Matching Multiple Values:

Attribute*=Value (Wildcard match anywhere in value)

Style any elements that have a Title attribute that contains "Shop"
[title*="Shop"] { color: orange; }

Match any DIVs that have an ID containing "Emw3"
div[id*="Emw3"] { color: orange; }

Attribute^=Value (Begins with value)

Style any elements that have a Title attribute that begins with "Home"
[title^="Home"] { color: orange; }

Style any <a> elements that have an HREF attribute that begins with "Emw3.com" (so this will also match any deep links)
a[href^="https://emw3.com"] { color: orange; }

Attribute$=Value (Ends with value)

Style any elements that have a Title attribute that ends with "sales"
[title$="Sales"] { color: orange; }

Attribute~=Value (Match a list - values separated with spaces)

Style any elements that have a Title attribute that contains "sales", optionally the title can contain other words separated with spaces.
[title~="Sales"] { color: orange; }

Attribute|=Value (Begins with value - separated with dashes)

Style any elements that have a Title attribute that starts with "sales", optionally the title can contain other words separated with dashes.
[title|="Sales"] { color: orange; }

Multiple attribute selectors

Multiple attribute selectors can be listed, in which case, all of them must match:

h1[rel="nofollow"][title^="Sales"] { color: orange; }

Attribute selectors are frequently used for styling forms:

input[type="text"] {…}
input[type="button"] {…}

“Natural selection, as it has operated in human history, favors not only the clever but the murderous” ~ Barbara Ehrenreich

Related:

Class and ID - CSS selectors.
Pseudo classes - Format Anchor links and Drop Caps.
Selectors - W3C


Copyright © 2013-2022 Emw3.com
Some rights reserved