Is There Any Pros and Cons If I Use Always CSS Class Instead CSS Id for Everything

Is there any pros and cons if i use always CSS Class instead CSS ID for everything?

One big difference: in CSS, a class has a lower importance level than an ID.

Imagine that each specification in a CSS declaration added a certain number of points to that declaration's value. Let's say the points go something like this (totally made up, but whatever):

  • Tag name ('a', 'div', 'span'): 1 point
  • Class name ('.highlight', '.error', '.animal'): 10 points
  • ID ('#main-headline', '#nav', '#content'): 100 points

So, the following declarations:

a {
color: #00f;
}

.highlight a {
color: #0f0;
}

#nav .highlight a {
color: #f00;
}

are worth 1, 11, and 111 points (respectively). For a given tag, the declaration with the highest number of points that matches it "wins". So for example, with those declarations, all a tags will be blue, unless they're inside an element with the "highlight" class, in which case they'll be green, unless that element is inside the element with id="nav", in which case they'll be red.

Now, you can get yourself into tricky situations if you're only using classes. Let's say you want to make all the links in your content area blue, but all the links in your foo area red:

.content a {
color: #00f;
}

.foo a {
color: #f00;
}

By my previous (made up) scale, those both have 11 points. If you have a foo within your content, which one wins? In this situation, foo wins because it comes after. Now, maybe that's what you want, but that's just lucky. If you change your mind later, and want content to win, you have to change their order, and depending on the order of declarations in a CSS file is A Bad Idea. Now if, instead, you had the following declaration:

#content a {
color: #00f;
}

.foo a {
color: #f00;
}

Content would always win, because that declaration has a value of 101 (beating foo's 11). No matter what order they come in, the content declaration will always beat the foo one. This provides you with some very important consistency. The winners won't arbitrarily change based on changing orders in the file, and if you want to change the the winner, you have to change the declarations (maybe add a #content in front of the .foo declaration, so it will have 111 points).

So basically, the differences in values are important, and you get a lot of inconsistency and seemingly arbitrary winners if you just use classes.

Why not simply use class in html/css all the time instead of id?

A few reasons:

1: Id's are for targeting one element, while classes are for multiple

Example:

<div id="test">This is red</div>
<div class="test"></div>
<div class="test"></div>

#test{
background:red;
}

2: Id's overrule classes in CSS

Example:

<div class="test" id="test">Test</div>
#test{
background:red;//Overrides, even though it is higher in the document
}
.test{
background:blue;
}

3: Id's are used for anchor links in HTML

Example:

<a href="#test">Link to test</a>
<div id="test"></div>

4: Id's are easier to select with JavaScript

<div id="test"></div>
<div class="test"></div>
document.getElementById("test"); //returns the element
document.getElementsByClassName("test"); //returns a HTMLCollection, which is like an array

CSS Best Practice about ID and Class?

I guess they always use the id in examples because it's less ambiguous. You know that they're talking specifically about that one element and its styles.

In general, the rule of thumb is that you should ask yourself: "is there more than one element which requires the same style, now or at any time in the future?", and the answer is even "maybe", then make it a class.

why do people use classes in html when they only have one of the element

If the site is in-development, this may mean that they plan to use more of that same item.

There isn’t really a difference otherwise, a class can be applied to multiple items, but an ID can only be applied to one item.

I use classes as a matter of personal preference, unless I plan to use JS with that (single) element, then it is easier for me to use an ID.

Why selecting by ID is not recommended in CSS?

CSSLint gives a guide to why they make their recommendations:

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. Additionally, IDs impact your specificity and can lead to specificity wars.

(From Disallow IDs in selectors.)

Basically, if you structure your code to use classes rather than IDs, your code can be more general and reusable, which is generally a good thing. Furthermore, specificity is a hard thing to get your head around, and can cause bugs that are hard to find, so if you omit ID selectors, you're less likely to have conflicting rules resolved in unexpected ways.

When is it okay to use Id for styling?

I thought this well stated from the article CSS Lint is harmful

ID’s are extremely useful and you absolutely should use them. They are
the fastest way a browser can select a given element. They are useful
for in-page anchoring and if they’re already there in the markup then
use them as style hooks. They are also, oddly enough, perfectly
correct to use as long as they’re only ever one instance of that ID on
any given page.

Arguments about “selector specificity” are at best a stretch to
justify a bad rule. Author your CSS properly and you won’t fall into
any specificity traps. I can count on my hand the number of times
that’s been a problem for me in 6 years of coding CSS and HTML for a
living on various different types and scales of website.

The only time this rule could be called accurate is if you are using
ID’s to style a specific chunk of HTML with intent to allow its use
anywhere on the site. e.g., if you’re using it to style a HTML gallery
widget that a user can include on any page via their CMS. They may
specify more than one on a page. But, that’s the one and only time
it’s a concern.

The way you have it in your example is correct and it is ok to declare it multiple times in your css, you just dont want to use an id multiple time on elements.

Why is the id attribute needed when we have classes?

In a conforming document, you can rely on an ID that is in use always pointing to exactly one element. You don't have this guarantee for a class since a class is designed for use by any number of elements.

There are numerous use cases that all rely on a unique ID, including but not limited to:

  • Fragment identifiers (which can also be resolved with a named anchor but that feature has been deprecated in favor of just straight-up using IDs)
  • The for attribute on the label element
  • document.getElementById()

Using IDs in LESS

Yes. It's ok to have id element inside other id elements.

The generated .css will work.

Personally, I like to use as few id elements in my code as possible. The reasoning behind this, is how some browsers don't like it when you have multiple instances of the same id on the page. I find that using classes is more flexible.

Here's a relevant stack overflow question that mentions on ids vs. classes:

Is there any pros and cons if i use always CSS Class instead CSS ID for everything?

Are separate css files always considered superior to inline styling? Even for one-off adjustments?

Yet, the internet tells me it is always preferred to keep all my style information in .css files. Who's correct?

You do realise you're asking the internet here...? ;)

Having had to redo several websites where styling had been applied using inline tags, I can say without any hesitation that I would never, ever use them myself. They are a nuisance to maintain and unless you're keeping a close record of where and what you have applied the inline styles, it is difficult to ensure that your changes to global css files will be respected throughout the site.

If you do need page-specific css classes and you don't want to put them in the global css file, add them to the page head in a <style> element. Putting all your css in a single file has the advantage that the users' browsers will load the file and cache it, so that it won't need to be reloaded on other pages of the site.

If you are finding you have a lot of tweaks to make all over the place, it suggests the design may need rethinking or refactoring. This is particularly the case with margins and padding--you can make a lot of work for yourself by choosing the wrong combination to apply spacing to your document elements.

What's the point of using an id selector?

Here are a few reasons that come to mind:

Direct Linking.

You can link directly to a specific element on the page by adding the id to the end of the url. See this post for examples: Link to an element within the current page

Javascript Compatibility.

A lot of JS libraries utilize the differences between classes and IDs. For example, they will treat classes as an array of elements, assuming you want to iterate over all of the instances of that class. IDs on the other hand are assumed to be singular, and whatever functionality you are trying to achieve will look for only a single instance. This has minor (almost unnoticeable) performance benefits, but can also break many functions if not used correctly.

Specificity.

When targeting elements on a page, specificity always comes into play. Since IDs and classes have different weights, using them incorrectly can cause problems when you are trying to keep styles from over-writing each other. See here for more info: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Browser Compatability.

While browsers are getting better at conforming to modern CSS standards, there are always going to be quirks. Not every selector works in every browser and some CSS tricks may break when your users visit your site using an old version of IE or some random build of Safari. That being said, IDs will always work, no matter what. This may not relate to your specific case, but could help prevent headaches down the road.

Best Practices/Readability.

Most importantly IMO, is the readability aspect. When looking over another developer's code, I assume when I see a class being specified in the CSS that whatever styles they have set will affect multiple areas of the page. This means I shouldn't just go changing things without further research. Opposite of that, if I see an ID being used, I can assume that any changes to that particular style will affect only that one area, and there shouldn't be any surprises for me down the road.



Related Topics



Leave a reply



Submit