Jason Melgoza is a Husband, Father and ~Designer at RightScale.

CSS3 Selectors

When taking a close look at the markup from Twitter’s Bootstrap (an amazing project by the way) I came across this little nugget.

[class*="span"] {
  float: left;
}

Which targets this little stub of HTML.

<div class="span3">
 ...
</div>

My initial re-action was “What the Hell - span does not equal span3!”, but after calming down I did little digging and I’m now pleased to learned something new about CSS - and that is CSS3 Attribute Selectors.

Put best by this SitePoint reference article.

CSS3 Attribute Selectors give us the ability to make partial matches to attribute values—we can match strings at the start, end, or anywhere within an attribute value.

Here’s a sample of these three CSS definitions:

To target a selector that starts with the value “span” use the following

[class^="span"]

For a selector that ends with “span” use

[class$="span"]

and for a selector that just plain contains “span”

[class*="span"]

Now if you like to get little creative with your stylesheets (and who doesn’t - really?) then the benefits here are clear. With this we can target a large range of elements, such as grid columns, with less CSS.

Like more on the subject? Here’s a 2006 post from Roger Johansson’s 456 Berea St with a larger list of selectors.

07 Feb 2012