Reputation: 36506
In css, I have seen both div.selector and selector being used to define styling rules for a specific selector.
What's the difference between the two and what are the reasons I should consider when adopting one over the other when writing my own css files?
Upvotes: 3
Views: 360
Reputation: 9281
As mentioned so far, prefixing your class with its element name (ie: div.selector) will select only elements which are divs, but exclude anything else. With this in mind you can create classes which can be applied to multiple elements and/or target a single element.
In terms of readability, prefixing your classes can help you and your team identify what the element is from within the css. However in terms of general best practise and performance it is commonly advised that you try to refrain from prefixing your class and id declarations as it causes additional work for your users' browser engine.
By prefixing your classes (ie: div#selector or div.selector) your browser has to locate the class and then identify whether it is of the div type). Whilst the time required to do this might be negligible, I feel it's still worth mentioning.
Below are a few helpful links on the matter of performance and practice:
https://developer.mozilla.org/en/Writing_Efficient_CSS and http://css-tricks.com/efficiently-rendering-css/
Upvotes: 1
Reputation: 72672
div.selector
is a more specific selector than .selector
.
For example of you have this HTML:
<a href="" class="selector">Link</a>
<div class="selector"></div>
The selector div.selector
only matches the div where .selector
selects both elements.
Upvotes: 3
Reputation: 382696
div.selector
targets only div
elements with a class of selector
..selector
targets ALL elements with a class of .selector
not just DIVs
So prefix element with tag name if you KNOW that's the one you will be applying css to. The later approach is more generic and targets all elements with specified class. However, you should be specific whenever you can.
If you know only div
elements will have .selector
class, going specific is better in terms of performance eg div.selector
rather than .selector
which will look for all elements on the page but will eventually apply those styles to DIVs
only.
Upvotes: 9