Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Best Practices: Classes for all elements or styling by parent class?

Tags:

css

So, I was wondering about the following: I have some main content div and a sidebar div and the CSS looks as follows:

.main{
 width: 400px;
 height: 300px 
}
.sidebar{
 width: 100px;
 height: 300px;
}

I will not include now all the floating properties, since I am only interested in the following: If I have a p element in both of them and I want them to have different styles, shall I give the paragraphs different classes or shall I define the style for them like this:

.main p{
 color: blue;
 text-align: right;
 font-family: ...
}

And then for .sidebar p I would define something else... The alternative would be to define a class p.myclass and define the style there. I am trying to understand what a better practice is. Obviously I need less markup if I have 30 p elements in one of the elements with the first method, since I would have to give them all a class. On the other hand, I create CSS that I can only "use" for that parent element, instead of having a general definition that I can apply in more places in the site... I noticed that in a lot of "big" websites, almost every single html element has its own class... Any ideas?

like image 314
cssmaniac Avatar asked Sep 29 '09 12:09

cssmaniac


2 Answers

I would definitely go ahead with the containment selector in the case you give. Fewer spurious classes in the markup is easier to maintain, and the rule ‘.main p’ says clearly what it does. Use your judgement to whether more complicated cases are still clear.

Note that ‘.main p’ selects all descendent paragraphs and not just direct children, which may or may not be what you want; accidentally-nested descendant matches are a potential source of bugs (especially for cumulative properties like relative font size). If you want only children to be selected you need ‘.main>p’, which unfortunately does not work in IE6.

This is one reason why many sites go crazy with the classnames: the more involved selectors that could otherwise be used to pick out elements without a classname, tend not to work in IE.

like image 154
bobince Avatar answered Sep 22 '22 10:09

bobince


I vote for .main p and .sidebar p because:

  • It most clearly expresses your intention, as you're expressing it in English
  • It reduces the number of explicit classes you need in your HTML
  • If you change your mind later and want an explicit paragraph class with that style you can just add it: .main p, p.foo
like image 21
Nathan Long Avatar answered Sep 22 '22 10:09

Nathan Long