views:

114

answers:

4

What are the best practices with respect to styling HTML elements using CSS? What's the preferred granularity for styling HTML elements? i.e., do you have lots of

div.searchbox input

div.searchbox p

div.searchbox p.help

OR

input.searchbox

p.searchbox

p.searchboxhelp

Which css code is considered easy to maintain? Is using grid frameworks and reset considered best practice?

Thanks

+6  A: 

I totally prefer the first approach. The search box is a defined entity with specific styling rules. If the search box has unique visual settings that no other element on the page has, which is usually the case, that is the way to go.

If there are any global rules in addition, you'd define them globally in a different section of the style sheet:

input { font-size: 16px; color: blue }

If there are any rules that a number of input elements on the page (not all in the search box) should share (e.g. "the search input field, and the login input fields should stand out a bit, and have a yellow background") you can create a global class in addition to the "local" rules:

input.highlight { background-color: yellow }

and add that class definition to every input:

<div class="searchbox">
 <input type="text" class="highlight">  <!-- Gets applied the "highlight" 
                                             and the "searchbox" styles -->
</div>

But the basic foundation should always be a "local" set of rules as you do in your first example IMO.

Pekka
A: 

The two sets of examples you gave do not produce equal results. div.searchbox input selects a child input element of a div that has an attribute of class="searchbox" while input.searchbox selects an input element that has an attribute of class="searchbox". In the first example, the div has the class attribute, but in the second example, the input has the class attribute. CSS-Tricks has an article on multiple CSS selectors that addresses this idea specifically. As they are not equal, there may be times to use either, and neither one is more correct than the other.

If your question is about the specificity of CSS selectors, CSS-Tricks has an article on specificity that will probably explain the general idea better than I could here:

The point here is you want to be as specific as it makes sense to be every chance you get.

I prefer to use multiple CSS selectors over adding style classes to the HTML. In Pekka's example, you may find yourself editing the HTML in addition to the CSS when making minor style changes that have nothing to do with the meaning of the HTML document.

HaleFx
A: 

I normally try to reach a compromise between:

input.searchbox

and

body div#layout div#main div#content div.section div.subsection form input.searchbox
Álvaro G. Vicario
A: 

I found this very useful.

Vasu