[element].[classname] vs. .[classname] in CSS
June 20, 2014 8:11 AM   Subscribe

If I plan to define a CSS class to style only one type of element, is it a good idea to write the selector, for example, as img.gallery rather than simply .gallery? Seems that it would make the CSS a little more human-readable.
posted by markcmyers to Technology (7 answers total) 3 users marked this as a favorite
When you're getting that granular, it's a matter of preference, really.

I will say that in this particular example, since it's an img, I would go ahead and include it. Styling images is different, in minor ways, than styling other kinds of HTML elements, and it would be a useful piece of info for any future editors to have.
posted by o2b at 8:21 AM on June 20, 2014

img.gallery and .gallery aren't exactly identical—CSS has some arcane rules about selector specificity and precedence—but that's almost certainly not going to be an issue in this case. So, yes: “programs must be written for people to read, and only incidentally for machines to execute.”
posted by Zozo at 8:22 AM on June 20, 2014 [1 favorite]

There were some pretty good answers in your previous question.
posted by bcwinters at 8:23 AM on June 20, 2014 [1 favorite]

So there were, bcwinters. I'm abashed.
posted by markcmyers at 8:38 AM on June 20, 2014

It's a matter of precedence.

If you look at the CodePen here, styles applied in .gallery {} won't reset styles set in img.gallery {} because a selector including element takes precedence. img.gallery is more specific than .gallery and therefore overrides it.
posted by theraflu at 9:27 AM on June 20, 2014

CSS rules are parsed from right to left (which I always find a little counter-intuitive) so if you use img.gallery the browser will first look through the DOM for every element with a class of .gallery, and then will check that each of those is an IMG

If you just use .gallery that second step is missed out and the page will render a tiny bit faster.
You could improve the readability by just changing the class name to .img-gallery
posted by Lanark at 10:26 AM on June 20, 2014 [2 favorites]

« Older Tedium, tedii, tedio   |   How Much Does this Job Have to Pay to Maintain... Newer »
This thread is closed to new comments.