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:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay