views:

38

answers:

2

Given

<div class="foo">
    <span class="bar"></span>
</div>

I've always defined the CSS classes as:

.foo
{

}
.bar
{

}

Is specifying the object important, or ultimately for readability so you can quickly see which sort of element you are searching for when editing? IE:

div.foo
{

}
span.bar
{

}
+5  A: 

It will be important for element specificity.

.foo targets any element that has a class of "foo".

div.foo targets only <div>s that have a class of "foo". That means other elements with that class aren't selected.

If you're sure only one kind of element will ever bear a given class, I guess there's nothing wrong with prefixing the class selector with the element name for readability, or leaving it out completely if you're lazy to type.

However, if you think other elements might bear this class — for instance if it's a pretty generic name like left, larger-font or sep, it's a good idea to do this so you're sure you're styling the right elements.

If there are any common styles shared by any elements with a given class, you specify just the class selector and add the common styles there, then after that specify any styles that pertain to each individual element. For example:

.foo { /* Generic styles for foo class */ }
div.foo { /* Styles for <div>s with foo class */ }
blockquote.foo { /* Styles for <blockquote>s with foo class */ }
BoltClock
Why would you have another element with the same class if it's not defined?
Tom Gullen
I've expanded on my answer.
BoltClock
I use this `div.foo` notation when I have styles I want to recreate in different elements like `div.blue-text` and `span.blue-text` for example.
Kyle Sevenoaks
Excellent answer, thank you!
Tom Gullen
+1  A: 

In addition to Boltclock's answer, there's a difference in how css walks through the DOM, which can have an effect on the processing speed of the stylesheet. For example, Mozilla advises not to use the element before the class: https://developer.mozilla.org/en/Writing_Efficient_CSS

In case of id's I tend to use it anyway though, purely for readability reasons.

Litso