Posted over 9 years ago. Visible to the public. Repeats. Linked content.

CSS: Matching against attributes and their values (or parts of them)

You probably know that you can use CSS selectors to match against elements and their attributes, such as:

a[title] { /* any <a> that has a "title" */ } a[data-fancy="true"] { /* any <a> that has their "data-fancy" attribute set to "true" */ }

But there is more: You do not need to match against "full" attribute values but can match against parts of them.

They work Archive in all somewhat modern browsers, and IE9 or later.

Exact match (CSS2)

[foo="bar"] (matches <div foo="bar" />, but not <div foo="bar baz" />)

Exact match for whitespace-separated values (CSS2)

[foo~="bar"] (matches <div foo="bar baz" />)
For the class attribute, this is the same as .bar.

Match against beginning of value (CSS3)

[foo^="bar"] (matches <div foo="barington" />)
Note that matching a class is not as straight-forward, since the class attribute usually contains several white-space separated values.
To match the beginning of a class properly, use this combined selector: [class^="bar"], [class*=" bar"]. It matches bar either at "beginning of attribute" or "preceded by white space".

Match against end of value (CSS3)

[foo$="bar"] (matches <div foo="foobar" />)
To match the end of a class, use [class$="bar"], [class*="bar "]. See comment to "match against beginning".

Match against value substring (CSS3)

[foo*="barb"] (matches <div foo="foobarbaz" />)

Match against beginning of hyphen-separated value list (CSS2)

[foo|="foo"] (matches <div foo="foo-bar" /> and <div foo="foo" />)

There is also a CSSDesk Sandbox Archive for you to play around with these.

Example: Style absolute/relative links via CSS

If your application always uses relative paths to link to its own content (which usually the case), you can highlight links to the outside world by matching against the beginning of their href attribute.

a[href^=http] { border: 1px solid red }

Fun fact: CSS4 might introduce a local-link pseudo class Archive for that certain case.

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Arne Hartherz
Last edit:
about 1 year ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more