no. 4| 05.04.2014 |
Classes vs. IDs
The general idea with both of these CSS selectors is that they let you add more specific, custom targeting over and above the standard elment selectors. For example, you might have part of your page design that requires a different visual treatment for a paragraph. Classes and IDs can be attached to the HTML element you want to target, and then the CSS file can specify a collection of styles that will apply to only HTML elements that have the associated class or ID.
As an example, here's what the HTML would look like if you added a class to a paragraph tag:
<p class="mynewclass">The internet was made for cats. They've been waiting and waiting.</p>
And the associated CSS file would then have to contain:
.mynewclass {
color: pink;
font-family: cursive;
}
Adding an ID works pretty much the same way, but with a different term / symbol combination:
<p id="mynewid">The internet was made for cats. They've been waiting and waiting.</p>
And the associated CSS file would then have to contain:
#mynewid {
color: pink;
font-family: cursive;
}
So, use class="something" in your HTML and a period in the CSS for classes and id="something" and a pound sign for IDs.
What's the difference? Why wouldn't you just use IDs for everything? The main difference between classes and IDs is that an ID can only be used once in an HTML document, but classes can be reused. So you could have lots of different paragraphs that used a class tag, but only one paragraph could use any particular ID.
Because of their specificity, IDs are generally used to target a unique component of a page. Like a sidebar, or a navigation bar. You'll often see them used with <div> tags that contain a major page section. The elements contained in the div can then be targeted in the CSS by combining the ID selector and standard HTML element selectors. IDs are also important on pages that use Javascript. The can provide the specificity needed for JS code to target and manipulate the correct page element.
Chris Coyier of CSS-Tricks has a helpful way to understand and remember the difference between classes and IDs: Think of classes like bar codes - you could have lots of items with the same barcode. An ID is more like a serial number - it's unique, and identifies only one thing.