Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Best Practice about ID and Class?

Tags:

css

I've been dipping into SitePoint book concerning CSS.

The thing that struck me about the examples was the use of ID as a CSS selector.

Some bits of CSS design I've done, I've always found it easier and more versatile to use Class as the selector.

Maybe its a .Net thing as we don't always have control of the ID of an element...

Is the best practice here to use CLASS or ID as the selector?

like image 248
Mesh Avatar asked Nov 18 '08 12:11

Mesh


People also ask

Is it better to use ID or class in CSS?

The basic rule that you need to keep in mind while using classes and ids in CSS is that, id is used for single elements that appear on the page for only once (e.g. header, footer, menu), whereas class is used for single or multiple elements that appear on the page for once or more than once (e.g. paragraphs, links, ...

Can we use ID and class together in CSS?

Yes you can. You just need to understand what they are for, the class is more general and can be used several times, the id (is like your id's) you can use it only once.

Which has more priority ID or class in CSS?

Class and ID selector example If more than one rule applies to an element and specifies the same property, then CSS gives priority to the rule that has the more specific selector. An ID selector is more specific than a class selector, which in turn is more specific than a tag selector.

When should you use IDs vs classes?

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.


1 Answers

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.

like image 151
nickf Avatar answered Sep 21 '22 23:09

nickf