[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 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 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 [1 favorite]

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

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

It's a matter of precedence.

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

CSS rules are parsed from right to left (which I always find a little counter-intuitive) so if you use 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 [2 favorites]

« Older I'm teaching a three-hour dail...   |  I am considering a job offer t... Newer »

You are not logged in, either login or create an account to post comments