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:
What is a CSS class? A CSS class is an attribute used to define a group of HTML elements in order to apply unique styling and formatting to those elements with CSS.
At its most basic level, CSS consists of two components: Properties: These are human-readable identifiers that indicate which stylistic features you want to modify. For example, font-size , width , background-color . Values: Each property is assigned a value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With