2

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

3
  • 1
    Is your example correct? 'div.searchbox p' is not the same as 'p.searchbox'.
    – Rob
    Commented Mar 24, 2010 at 12:03
  • 1
    he's asking a very relevant question though, i.e. should we scope by containing divs or attached classes? Commented Mar 24, 2010 at 17:21
  • 1
    If you use something like lesscss.org, then it makes it a tad bit easier, and all of the code produced is as in your first example. Commented Mar 24, 2010 at 17:36

2 Answers 2

6

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.

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.