CSS Basics: Using ID and Class attributes?

Hello everyone,

I have never figured completely how to use these properly.

I usually use #ID as ‘containers’ and ‘sub containers’, and I use .class for other elements inside the said containers. For example

#container{
margin: 0 auto;
}

.nopadding h1{
padding: 0;
}

<div id="container">
   <h1 class="nopadding">No Padding Heading</h1>
</div>

I have no idea WHY I used them in this manner; sometimes I randomly these in different situations.

Hi, if you do .nopadding h1, it is selecting an <h1> element that is a child of hte .nopadding element. Make it “h1.nopadding” :slight_smile:

Hi, i’m not sure if i understand your question. Do you mean when to use id’s and when classes and what the difference is between them?

This will bring you up to speed if it’s the case.

It should be h1.nopadding, no?

yes h1.nopadding :slight_smile:

It goes to show how shaky my fundamental knowledge is. I will have to solidify it by reading more articles.

Thanks for the link Luki be!

Yes, h1.nopadding, as I said. The h1.nopadding wil select an <h1> element with the class"nopadding"

Just practice CSS and it’ll all start to click into place. It can be a steep learning curve for beginners ;).

As a general rule, I use classes for elements that I know I’ll be using multiple times within a document. All other elements that only appear once within a document will be given the unique identifier (ID).

I do try to avoid using IDs and classes wherever possible, however. Sometimes you can accomplish a lot by just using the cascade. :slight_smile:

Your above example does not work because the code reads (in plain English):
“Apply this style to all H1 elements that are descendants of an element (ancestor) with a class of noPadding”.

-------------#container .noPadding----------

---------------------h1---------------------


<div id="container" class="noPadding">
  <h1>I'm a descendant of .noPadding</h1>
</div>