In designing the HTML and CSS for a page, when should I use
img.className
versus
.className
versus
#idName
or some other variant?
Are there guidelines or recommendations?
Summary from answers
Thank you to all answerers – there is some excellent stuff here!
- make CSS as specific as possible
- use an OO approach
- order: #id, tag, tag.className, .className
- when to use each selector, also class/ID comparison
- give selectors names based on purpose, not what they look like
- use advanced selectors for smaller code, leave CSS classes for exceptions/overrides only
- manage ASP.NET munging ID
In general you should be as specific as the item demands.
There is no general rule, it depends on the style in question.
A lot of people will recommend you keep to the lowest specificity with the theory that this allows the maximum cascading reuse but this is absolutely toxic in real world situations where you have multiple developers all working on slightly different versions of what a
.foomight look like. Pollution from inheritance you did not want leads to massive bloat in trying to undo that locally or time-loss in refactoring.The best guideline I always offer is to try and think of CSS in OO terms: class selectors map to interfaces more or less, tags map to classes, and ID selectors map to instances. Consequently decide if the style you want to apply really applies to that thing, all things like it, or anything which wants it.
I also strongly encourage you to make use of high level IDs on wrapper elements so you can write selectors in a namespace like fashion (i.e.
#foo .bar,#foo .bazwhere#foois unique to a page or set of page designs) which allows you both a level of specificity which reduces cross-design pollution and a level of generality which lets you make the most of cascading CSS reuse.Best of both worlds.