Posted about 6 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:

Copy
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 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 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.

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

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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
6 months ago
by Dominik Schöler
Keywords:
regexp
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 cookies to improve usability and analyze traffic.
Accept or learn more