Assume that I have some HTML page, and a corresponding CSS file. I'd like to add rounded corners to some elements. I want to alternate background colors on every other section. I want to add a hover state for each section heading. So forth and so on - I keep styling and styling and styling.
It occurs to me that there are three extremes, where it concerns the "who, what, when, where, why and how" of distributing CSS rules over the markup by class, by id, and by hierarchy.
Extreme #1: Every style rule is based on an ID.
Extreme #2: Every style rule is based on a class.
Extreme #3: Every style rule is based on the DOM hierarchy.
Clearly, the zen of front-end web development would include a healthy balance of class reuse vs. unique rules vs. hierarchy, because any of the three extremes would wreak havoc on browser performance, maintainability, and code size. I think. Or am I wrong? How to tell when a new .class
is necessary, or the style rules you want to apply can be safely shoe-horned into an existing definition? When are two #id
rules similar enough that you should pull common code out into a class? When do you "fork" a class (sometimes you keep the original, and add derivations for all deviate situations ("percolate" in OOP terms), and other times push common rules down into each of the several disjoint deviations - clearly this depends upon the nature (ie, number of rules involved) in the deviation itself). Are there just circumstances for using purely hierarchical rules?
Question: Are there any rules of thumb governing this sort of debate? What is your experience and/or advice? Are there good articles, resources, books, lectures (bonus points for "tech talk" style videos), or other content available on the topic? I'd like to keep the discussion grounded in a few key points (although any commentary is welcome), in no particular order:
- Maintainability (ease of reading, modifying, and adding code)
- DRY (Don't Repeat Yourself)
- Time efficiency (time-to-onload; progressive rendering)
- Space efficiency (combined size of the markup & associated styles)
Do yourself a favor, check out SASS.
While there are pros and cons to compiling your CSS, the gains from having real variables, mix-ins, and helpers in your pre-compiled CSS is definitely worth at least passing consideration.
来源:https://stackoverflow.com/questions/4550511/markup-style-best-practices-how-to-efficiently-distribute-style-rules-over-css