simonewebdesign

Fuzzy matching with CSS3

There are special cases where a simple CSS selector is not enough. Like yesterday, when I wanted to match all the uploaded images in my blog, regardless of the container and the content.

Let’s see an example markup:

<p>
  <a href="/blog/wp-content/uploads/2012/11/cat-eat.gif">
    <img src="/blog/wp-content/uploads/2012/11/cat-eat-300x225.gif"
         alt="" title="Cat Eat" width="300" height="225"
         class="alignnone size-medium wp-image-361" />
  </a>
  <a href="/blog/wp-content/uploads/2012/11/cat-help.jpg">
    <img src="/blog/wp-content/uploads/2012/11/cat-help.jpg"
         alt="" title="Cat Help" width="500" height="457"
         class="aligncenter size-full wp-image-367" />
  </a>
</p>

How do we match only the images?

Well, there are many solutions. The simplest is certainly to use the img selector; but this way we’d match all the images, which isn’t our goal. We just want to match the uploaded ones.

Let’s examine the markup above. See, WordPress uses some classes in order to apply the correct size or alignment, and finally applies a unique class with a progressive number (wp-image-*), just in case we want to match a single element. So we could do this:

.wp-image-361,
.wp-image-367 {
  /* some fancy CSS code here */
}

The solution above works, but it is not handy because – as you may have guessed – we should update the selector each time we upload a new image.

Hey, are we supposed to hard-code all the classes?

No, absolutely! That’s an absurd solution. Let’s explore other options.

The official W3C Selectors Level 3 specification offers a freaky set of selectors, for the joy of the craziest web designers!

In our specific case, this would do the trick:

img[class^="wp-image-"] {
  /* matches an img element whose "class" attribute value
  begins exactly with the string "wp-image-" */
}

Note that I’m talking about CSS3, so if you need to support older browsers, don’t lean on it.

Cool. What else?

The table of selectors presents a whole bunch of possibilities, even though the usefulness isn’t always evident. But I’m sure you can find an example for every selector listed there. So, whether you are a CSS wizard or not, my final advice is: go create cool stuff, because practice makes perfect.

View this page on GitHub