Day 35 to 39 - Updates + 1 CSS trick, attribute selectors!

Jul 29, 2014

It's been pretty crazy this week so I've just been doing some "easy" #summerofme updates. I fixed some responsive bugs on the site and did some reading. Keeping it simple. But I feel like I should share something. So here's a little CSS trick for reducing class names. How many of you have done this before?

<button class="btn btn-blue">Click me!</button>
<button class="btn btn-green">Click me!</button>
.btn {
  //shared styles
}
.btn-blue {
  //specific styles
}
.btn-green {
  //specific styles
}

BUT, if you use an attribute selector combined with an asterisk, [attribute*=value], it will match every element with the attribute value containing the specified value. The asterisk is a univeral selector. So the above can be changed to:

<button class="btn-blue">Click me!</button>
<button class="btn-green">Click me!</button>
[class*="btn-"] {
  //shared styles
}
.btn-blue {
  //specific styles
}
.btn-green {
  //specific styles
}

No more extra class! But to be safe, one more selector should be added. The caret symbol. It's used in regular expressions to designate the beginning of a string. What if your HTML looked like this?

<button class="some-class button-blue">Click me!</button>
<button class="button-green">Click me!</button>

The current selector won't recognize the btn-blue because of the space between the classes. Update the selector to add another attribute selector, with the caret symbol.

[class*="btn-"],
[class^=" btn-"] {
  //shared styles
}
.btn-blue {
  //specific styles
}
.btn-green {
  //specific styles
}

Ta da!

I wish I could take credit for being clever but I found this by digging through the Bootstrap framework files :)

Home