(TOTAL NEWBIE) (CSS) Difference between setting things as a class vs an ID

(TOTAL NEWBIE) (CSS) Difference between setting things as a class vs an ID
0.0 0

#1

Hello All,

I am taking the front-end development course, and I am completely new to it (thanks for the help!). I just made it to the part about creating my first portfolio, so I have been reading up on Grids.

I don’t understand the difference between calling something via a class, or via an ID, and I don’t think the course work really mentions the difference. For example, making a grid as such:

div id=“firstGrid”>

#firstGrid {
display: grid;
grid-template-columns: minmax(100px, 50%) minmax(100px, 50%);
grid-template-rows: auto;
grid-row-gap: 10px;
grid-column-gap: 10px;
}

Versus calling a grid like this:

div class=“firstGrid”>


.firstGrid {
display: grid;
grid-template-columns: minmax(100px, 50%) minmax(100px, 50%);
grid-template-rows: auto;
grid-row-gap: 10px;
grid-column-gap: 10px;
}

These both yield the same result - what is the difference? What should I know to ensure I get my fundamentals right?

Thanks for the help!


#2

ID selectors have higher specificity than class selectors. In general, styles in selectors with high specificity can’t be overridden by those in lower specificity selectors.

For example, if you have a <p class="lead"> element and this CSS:

p {
  font-size: 14px;
}

.lead {
  font-size: 28px;
}

it will have a font-size of 28px, because the .lead class selector has higher specificity than the plain p selector. It’s the same idea with an ID selector, but with higher specificity than a class selector. But from what I’ve read, ID selectors are generally avoided because of their high specificity that’s hard to beat (I can’t remember where I read this, sorry)


#3

To add to what @kevcomedia wrote, this link explains why you may not want to style IDs.


#4

Thanks so much! That makes a lot of sense.