ID vs Class

I’m not sure I understand the difference between ID and class selectors - if that is what they are called.

I believe I have read that an ID must be unique, but unique to what? The page? And if so, what would happen if you used an ID in multiple places?

And a class can be used multiple times anywhere, right?

1 Like

Main I suggest validating a web page with multiple IDs and see if there are any errors or warnings shown.

https://validator.w3.org/

If you do not have a site there is an option to Validate by direct input".

Can you help me understand the difference between IDs and classes?

When I have read things like MDN it isn’t clear to me.

Use classes to target multiple elements of the same kind e.g. .cat
You can have as many as you want in any HTML page.

Use ids to only target one element e.g. #my-cat-rosie
There should only be one id of each kind in any given HTML page.

What happens if you use multiple of the same id in a page I’m not sure but I think it depends on the browser implementation to handle that misuse of HTML. Long story short don’t misuse it or you’ll get unexpected results.

@Andres_Vaquero,

This is a frustrating topic for me, and I’ll probably have to create another thread later on.

It seems like people almost always use classes, but I don’t see how/why because most of those items still only appear once on a page.

For instance, I have a “Product Title” which appears in 4 places on my website, yet only once on a given page, and on each page the styling is different, sit seems to me that i should use an ID even though lots of the code people share here would be marked up using a class.

Follow me?

Classes have more chance of being reused… chances are you’ll end up having a situation where you want to apply the same styles to different elements in a page. That’s why, even there is only one page title in a page at a given time, you might want to put those styles under a class called .heading and then you may run into a situation where you may need more than one in a page e.g. opening a modal window which also has a title heading.
Truth is that there are plenty more cases for classes than ids.

The power of ids is that they have preference over classes so if I had an element like this:

<div id="my-cat-rosie" class="cat">

and these styles:

#my-cat-rosie {
  color: white;
}

.cat {
  color: black;
}

the color set to that div will be white as ids get preference.

1 Like

@Andres_Vaquero,

Okay, let me dive a little deeper on this topic before bedtime…

I have a “productTitle” that appears in 4 places in my e-commerce site, and the font-size needs to be different for each.

Since the product title happens to be an H2 for all, I take this approach…

#wrapper_details h2{ }

#wrapper_store h2{ }

#wrapper_cart h2{ }

#wrapper_freebook h2{ }

That isn’t so bad, but below the product title I have things like “author name” which is a span, so there I need a ID or class to distinguish it from other spans (e.g. “published date”).

This is where I find my CSS not very “cascading”… :unhappy:

So for those, I would do…

#wrapper_details span#authorName{ }

#wrapper_store span#authorName{ }

#wrapper_cart span#authorName{ }

#wrapper_freebook span#authorName{ }

The assumption is that the “author name” is also styled 4 unique ways, so while a class wouldn’t break things, it adds no value.

And my larger issue is that I have a boatload of styles because I have all of these unique cases, and it feels like I am just doing old-fashioned HTML styling on a case-by-case basis…

In that case I would give the four different h2s’ their own class. Yes, you would still have four selectors with their own rules but you wouldn’t have a long chain of descendant selectors with all the heavy weight of the ID’s.

Like so…

h2.sm { }

h2.md { }

h2.lg { }

h2.xlg { }

With something like that you can reuse the h2s’ anywhere on the site without having a page name associated with them.

1 Like

Your dog is unique, but dogs are a class. You is unique, but all humans are a class. If there is many Peepers and you call for Peeper, there will be some confusion. I do not use an ID more than ONCE in an entire website or similar.

You are seeing for yourself there what kind of problems the different IDs’ for your page wrappers is causing you.

That’s really where the problem is starting. Surely those four page wrappers share some common styles that can be simply placed on one wrapper with a class.

.wrapper { }  /*common wrapper styles on all pages*/
.details { }
.store { }
.cart { }
.freebook { }

Then when you need a specific class for a page it would look like this in your html
<div class="wrapper details"> </div>

Now you can just say this for your h2s’

.details h2 { }
.store h2 { }
.cart h2 { }
.freebook h2 { }

And likewise for your authorName spans

.details span.author { }
.store span.author { }
.cart span.author { }
.freebook span.author { }

With all your unique styling you will still have several selectors, but if you get the specificity (weight) of the IDs’ out of there it will be easier to manage. You should be able to find styles that can be reused in many cases too. That’s why it’s best not to associate a page name to them if you can help it.

Pick a class name that describes what it’s doing rather than where it’s going. I used your page names on the spans because I don’t know what they are doing.

Now on your extra wrapper classes, the page names are fine. They will help you create page specific classes for other elements.

Point is, try to use as many utilty class names as you can so they are not bound by name to any specific page.

2 Likes

I don’t know as per usual and just guessing about the specific CSS but I prefer to use Three Letter Acronyms which can be used on all elements:

.fsi {font-size: initial;}
.fss {font-size: small;}
.fsm {font-size: medium;}
.fsl {font-size: large;}
.fsS {font-size: x-small;}
.fsX {font-size: x-largel; }

.bgs {background-color: snow;}
.bge {background-color: #eee;}

.fg0 {color: #000;}
.fg3 {color: #333;}
.fg9 {color: #999;}

This technique does involve class name chaining but reduces the CSS size considerably by Don’t Repeat Yourself and to me far more intuitive to read:

<h1 class="bgr fgy"> H1 Tag  red background-color and Yellow foreground text</h1>

<h2 class="bga fg0"> H2 Tag  aqua background-color and black foreground text</h2>

I am surprised nobody has mentioned the benefit of using an ID because JavaScript can easily find the DOM reference and apply subtle changes whereas a Class Name…

2 Likes

document.getElementById("id")
document.getElementsByClassName("class")[0]
shrug

1 Like

OK, I was trying to avoid this thread because it can lead down a rabbit hole I don’t really have the time to delve into, but it seems to have gotten away from the original question.

The basic difference between ID and class is there should only be one instance of an id on a page, but there can be multiple instances of class. Note the emphasis on should in the previous sentence. All of the browsers ALLOW you to use more than once instance of an id, but that’s not the way it’s supposed to work.

So you should never have this markup (from one of your previous posts)

#wrapper_details span#authorName{ }

#wrapper_store span#authorName{ }

#wrapper_cart span#authorName{ }

#wrapper_freebook span#authorName{ }

Now this is where the true power of CSS comes into place IF you plan it right. You need to get away from the concept of pixel perfection and allow yourself to think in relative measures and in terms of content instead.

So instead of

  • In details, I want the Authors Name to be 16px and the published date 14px
  • In the store, I want the Authors Name to be 12px and the published date 10px
  • In the card, I want the Authors Name to be 10px and the published date 8px
  • In freebook, I want the Authors Name to be 14px and the published date 12px

You think something like this

I would like to see the Authors Name be 10% bigger and the Published Date 10% smaller than the rest of the text in the details, store, cart and freebook sections

And to do that you would use simple classes for the author and the published date

.authorName { font-size: 1.1rem; } /* or 110%; */
.publishedDate  { font-size: .9rem; } /* or 90%; */

Then you would just set a base font-size in each of the wrappers

#wrapper_details {  font-size: 16px; } 
#wrapper_store {  font-size: 12px; }
#wrapper_cart {  font-size: 10px; }
#wrapper_freebook {  font-size: 16px; }

or even better, allow the user to choose the base font size and adjust accordingly…

#wrapper_details {  font-size: 1em; } 
#wrapper_store {  font-size: .8em; }
#wrapper_cart {  font-size: .75em; }
#wrapper_freebook {  font-size: 1em; }

The font size for the author and published date spans will be adjusted based on the font size of the wrappers. This keeps a consistent ratio for the same type of data across the board, which will be easier for you as it’s less to maintain, and for your customers as you’re providing a consistent experience.

3 Likes

To be abundantly clear: CSS allows you to. Javascript’s getElementById will still only ever return the first element.

Also, to quibble: 16px is not 110% of 14px, so you’re technically changing the outcome to fit the rules. :wink:

Proper declarations mean that you should have only one element with a given ID on a page. It’s an Identifier.
Proper declarations mean you should have an <html> tag around your code, and body tags, and thead and tbody… there’s a lot of ‘shoulds’ in HTML that browsers handwave.

Hence, why I said to get away from pixel perfection. The browsers will round, and for 95+% of the users, that will be close enough to not be a distraction.

Agreed, but not apropos to the discussion in place - she asked about CSS, not javascript. Hooking into javascript is another conversation.

Good advice from others above, but I agree with @DaveMaxwell that we got off topic.

I think I’ll create a new thread on what @Ray.H was talking about…

Back to what you were saying, Dave…

In my styles.css file, if selector called #wrapper_details h2{ } which is used in the script called “product-details.php” and then I have another selector called #wrapper_store h2{ } which is used in a separate script called “product-catalog.php” then I assume that is okay since the ID anchored style is unique in each script/webpage, right?

I believe what you are saying is that if I had a script called “report.php” and I referenced the selector #odd-row{background-color: green;} numerous times in a table, then that might work in the browser but would be improper styling, correct?

@DaveMaxwell, I am a MALE and not a “she”… :wink:

First, there should never be more than one instance of an ID per page, period. Second ID vs Class has more to do with specificity. EG:

<span id="my-thing" class="my-thing">MY THING</span>
.my-thing {
  color: red;
}
#my-thing {
    color: blue;
}

the my thing will always be blue as css reads left to right AND ID will always take precedence over class. Frankly I have not used an ID in anything in a LOOOOONG time.

Correct because you are not stylizing the same thing in those cases. While you are using the same element type, you are working in two different specific containers. This is valid.

Correct. The simple, hard and fast rule is there should NEVER be two objects with the same value in an ID attribute.

So the rules basically are:

  • If a style is being placed onto one and only one element (or container), then use the id selector.
  • If a style is being placed on multiple instances of the same element or container, then use a class.
  • If you have multiple id selectors which have a style attached to them, make them a class which allows one selector and greater flexibility.

Those rules are per page, but in reality should be placed over the course of your entire site. Relying heavily on id based selectors is just going to cause maintenance pains later on down the road because if you have to make any heavy markup structure changes, the chances of having to re-do both the markup and the styling goes up exponentially.

1 Like

and thus generally invalidate the benefit of using CSS over inline styling at all for those elements.
My personal stance is that using ID selectors is a last-resort option when all reasonable class-or-element-based means have been exhausted. And those cases would be exceedingly rare, in my experience.

3 Likes