Cascading Style Sheets Use "Id" or "Class"

Difference between id and class

The biggest difference is that a document can have multiple elements with the same class, but not with the same ID. An Identifier must be specific to a certain element within a document (i.e. full HTML page).

When applying CSS styling, some experts have recommended using classes over IDs to avoid specificity wars. CSS Lint (http://csslint.net/) recommends this.

The reason is that stylesheets are read from top to bottom, but IDs take precedence over class. This means that:

#stockexchange-id { 
color: blue;
}

.stockexchange-class {
color: red;
}

Would color the text blue, even though red comes later. Here's a good graphic explaining specificity: https://stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg.

If everything has the same specificity, and most styles are applied via a single class, it makes the CSS easier to reason about, since it will read from top to bottom without extra styles being mixed in different orders. It also makes it easier to override classes, which can be useful.

Finally, if you style based on classes, you can re-use the styling on the same page by applying the class to another element on the page. With IDs, since they are unique, you cannot do this. Even if you think an element is unique on a page (e.g. a Buy Button), this may not always be the case. A designer may request the same element again later in the page.

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.

CSS ID vs Class

It can only be assigned to one element in the page, but it can be used in multiple CSS rules. Class names can be assigned to multiple elements in the page.

CSS: are class and id interchangeable?

In answer to the question 'why do we use both classes and ids for CSS, when you're allowed to have a single instance of a class?', look at it this way.

We don't need IDs for CSS. We could just use single instances of classes.

But we need IDs for JavaScript. So, why not use them in CSS too?

Imagine a world in which IDs were there, but only used for JavaScript.

You'd have to code like this:

<div id="wrapper" class="wrapper">
<div id="nav" class="nav">

</div>
</div>

and so on.

What are the reasons to use the id attribute for CSS purposes?

The main reason I use ID tags is to communicate with people who are reading my code. Specifically, the ID tag makes it easy to reference whatever specific element they want to with complete peace of mind, knowing that any changes they make to it will only affect that one element.

There is also a more technical reason to use ID tags that you may not know. This information can be quite enlightening for those who are new to CSS.

The following outline illustrates exactly how the "cascading" nature of Cascading Style Sheets works. In this outline, start by comparing 2 CSS styles based on the uppermost criteria of the outline, ie "1. Winner = !important declaration." If one style is of higher priority than the other in that aspect, it wins. If they are the same in that aspect, continue down to the next criteria in until you find the differentiating factor.

  1. Winner = !important declaration.
    • Eg. #some-element {color: blue !important;} beats #some-element {color: red;}.
  2. Winner = Inline CSS.
    • Eg.:
      • <div id="some-element" style="color: yellow;}">some content</div>beats...
      • <style type="text/css">#some-element {color: red;}</style> and...
      • <link type="text/css" link rel="stylesheet" href="set-some-element-color-to-blue.css"/>.
  3. Winner = Greatest # of ID selectors.
    • Eg. #some-element#id-2 {color: blue;} beats #some-element {color: red;}.
  4. Winner = Greatest # of class, pseudo-class, and other attribute selectors.
    • Eg. .some-elements.class-2 {color: blue;} beats .some-elements {color: red;}.
  5. Winner = Greatest # of element names and pseudo-elements in the selector.
    • Eg. #some-element:hover {color: blue;} beats #some-element {color: red;}.
  6. Winner = Most recently read by the machine.
    • Eg.:
      • <style type="text/css">#some-element {color: red;}</style> beats...
      • <link type="text/css" link rel="stylesheet" href="set-some-element-color-to-blue.css"/> because internal CSS is read after external CSS.

CSS which takes precedence, inline or the class?

Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number three has the highest priority:

  1. Browser default
  2. Embedded and external stylesheets. Later has precedence over earlier. There IS NOT any inherent difference between embedded and external.
  3. Inline style (inside an HTML element)

Source (Edit: of original incorrect information, since corrected both here and there): w3schools

W3schools explains a lot about CSS and also goes through and shows examples of most things you can do with CSS. Always a good resource if you have questions about something. (Edit: debatable, they were the source of the original wrong answer.)

In CSS what is the difference between . and # when declaring a set of styles?

Yes, they are different...

# is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:

  • #foo {} will style the single element declared with an attribute id="foo"
  • .foo {} will style all elements with an attribute class="foo" (you can have multiple classes assigned to an element too, just separate them with spaces, e.g. class="foo bar")

Typical uses

Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.

Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {} which would only apply to <h1 class="error">

Specificity

Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box"> any rules for #sidebar with override conflicting rules for .box

Learn more about CSS selectors

See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.

EDIT: Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.

Can I use DIV class and ID together in CSS?

Yes, yes you can.

#y.x {
/* will select element of id="y" that also has class="x" */
}

Similarly:

.x#y {
/* will select elements of class="x" that also have an id="y" */
}

Incidentally this might be useful in some use cases (wherein classes are used to represent some form of event or interaction), but for the most part it's not necessarily that useful, since ids are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.

How to choose between `class` and `id`

Use id to identify elements that there will only be a single instance of on a page. For instance, if you have a single navigation bar that you are placing in a specific location, use id="navigation".

Use class to group elements that all behave a certain way. For instance, if you want your company name to appear in bold in body text, you might use <span class='company'>.



Related Topics



Leave a reply



Submit