DEV Community

Chloe
Chloe

Posted on • Originally published at cgweb.co.uk on

1 1

Attribute Selectors

Just a quick post on attribute selectors in CSS.

What is an attribute selector?

Attributes are part of HTML markup giving elements further details e.g href on a tags using CSS you can target these attributes and their values. Attribute selectors are shown by square brackets [] e.g.

a[title]{ 
color: #000000;
}

a[href="https://"] { 
color: #CC0000;
}

div[lang|="en"] { 
font-style: italic;
}
Enter fullscreen mode Exit fullscreen mode

The first example will match a tags with a title attribute, the second will target any a tags with mailto links and the final will match any divs with the exact lang value of en _or_ en followed by a hyphen.

Substring matching selectors

-[att^="val"] = begins with
-[att$="val"] = ends with
-[att*="val"] = contains

a[href^="https://"]{ 
background: green; 
color: white;
}

a[href$=".pdf"] { 
background: yellow;
}

img[src*="thumb"] {
 border: 2px solid #CC0000;
}
Enter fullscreen mode Exit fullscreen mode

I've created some examples are on codepen shown below:

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay