I'm never sure what the best (most efficient) way to select an element is.
Lets say I have the following layout (extremely simple example)
<div id="navigation">
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
#navigation ul {}
or assign a class to the UL?navigation ul li{}
or assign a class?#navigation ul li:first-child {}
or assign a class?I appreciate these questions are pretty much the same, but I'm curious when you should use a class and when not to.
In CSS, class and ID selectors are used to identify various HTML elements. The main benefit of setting class or ID is that you can present the same HTML element differently, depending on its class or ID.
Difference between id and class attribute: The only difference between them is that “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements.
You should use a class if you need to use the same selector more than once within a page or a site. While an ID is specific to a single element, classes can be assigned to multiple elements on a page or throughout the website. They are not unique.
IDs shouldn't be used in selectors because these rules are too tightly coupled with the HTML and have no possibility of reuse. It's much preferred to use classes in selectors and then apply a class to an element in the page.
There's no hard and fast answer here.
A general rule of thumb might be to use classes when you want to group certain elements together, treat them the same and using a class is the only means of doing it.
In your last example for instance, there is strictly no need for a class.
But, using a class in example 3 will result in better performance, as the browser will located the relevant items quicker. Traded off against this is a slight reduction in code-legibility.. If you have class names on everything then it becomes harder to read the rest of the markup.
In short, in what you have shown above, what you have written is fine imo.
You should read this article though which covers selector efficiency.
Basically the order of efficiency is as follows:
ID, e.g. #header
Class, e.g. .promo
Type, e.g. div
Adjacent sibling, e.g. h2 + p
Child, e.g. li > ul
Descendant, e.g. ul a
Universal, i.e. *
Attribute, e.g. [type="text"]
Pseudo-classes/-elements, e.g. a:hover
The performance difference between classes and Id's is normally irrelevant.
Going further down the list though, things slow down considerably.
This isn't an argument to add classes and id's everywhere - it just allows you to judge the trade-off between performance and maintainability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With