When to use the ID and Class CSS Attributes
With all of the different flavors of CSS out there I found myself getting confused on when to use ID's and when to use classes. I also wanted to educate myself on a practical easy to follow guideline that I could use throughout my website development and design process to make going through the code later on easier.
Here is what I came up with, I hope that you find it helpful.
HTML rules dictate that an ID identifies a single element in the DOM and each element can only have one unique ID. Then a CLASS classifies one or many elements in the DOM and each element can have multiple classes. So based on that you want to use an ID to designate main layout elements and use classes to define styles across multiple elements. Remember that !important overrides all, including inline styles. If you are still looking for a better definition then let’s say: An ID is typically used for a single instanced container/object, while a CLASS is applied to many objects.
Here are some real world usage examples:
#header { width:916px; height:130px; background:url(/images/header_bg.jpg) no-repeat; /*float:left;*/ padding:0 14px 0 0; position: relative;}
#header #logo { width:248px; height:78px; float:left; margin:25px 0 0 28px;}
#header #logo a { margin:0; padding:0;}
#header #sub-block { float:right; width:410px;}
#header #sub-block { margin:0; padding:10px 0 0 0; float:right;}
#nav - applies to the element with id="nav"
#nav div - applies to any div element inside the element with id="nav"
#nav .left - applies to any element with class="left" inside the element with id="nav"
#nav div span - applies to any span element inside a div element inside the element with id="nav"
.item span - applies to any span element inside the element with class="item"
.item .address - applies to any element with class="address" inside the element with class="item"
div.item - applies to any div element with class="item"
I find it easier to read and keep track of if I group ID's together and then add attribute instances as I go further into the CSS code. Hopefully that is what you get after looking at the code above.
Here are two additional ways to think of ID's and Classes:
1.) - ID = One Instance -- one student -- Per page
2.) - Class = Multiple Instances -- many students -- Per page
Here are some helpful naming convention examples:
ID's:
#header
#footer
#navbar
#section
#sidebar
#subnav
#menu
#content
#article
Classes:
.important
.warning
.validationError
.recent
.outOfDate
.inactive
.weekDay
.previous
.next
.first
.last
Happy CSS Coding
|