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 Show archive.org snapshot 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.
a[href^=http] {
border: 1px solid red
}
Fun fact: CSS4 might introduce a
local-link
pseudo class
Show archive.org snapshot
for that certain case.