ID's and Classes
A lot of web designers new to the field aren't aware of the differences between ID's and classes. So here's a fairly brief article outlining proper and improper uses of the two.ID's and What They're Used For
ID, short for fragment identifier, is a beautiful attribute, but it's very easy to use them improperly. You can only use an ID name once in any XHTML or HTML document. Duplicate ID tags will cause your page to fail validation, and can have negative effects when using JavaScript with them. Simply put, an ID is like the sticker that says "you are here" on a mall directory, and there can only ever be one of those.Browsers use fragment identifiers as well. If you want to place a link at the top of your page that will scroll the browser down to the content when clicked, simply add id="content" to the content element or header above your content and use the following anchor:
- <a href="#content">Go to the content</a>
Classes
Classes, like ID's, can also be used to in JavaScript scripts, but unlike ID's, they can be used multiple times in the same HTML document. This separation of content from presentation is what makes sites powered by CSS more robust, but some don't know the full extent to which they can use classes. Classes can not only be used more than once, but more than one can be used on an element:- .left {
- float: left;
- }
- .larger p {
- font-size: 125%;
- }
- <div class="left larger">
- <p>A tiny bit of content.</p>
- </div>
When to Use One or the Other
I take a different stance than most web designers when it comes to using ID's and classes. The vast majority of CSS coders use ID's for any elements that are simply used once on a page. However, I only use classes to style my websites, but, when I want to use an element in JavaScript, I use an identifier. From a presentational standpoint, styling elements with classes looks exactly the same as styling them with ID's, but the flexibility of classes offers a certain appeal even if I don't plan on using a class more than once on a page. Also, when I see an ID in my XHTML, it reminds me that there is some JavaScript that refers to that element.It's up to you, but so long as you implement classes and ID's properly, it is more or less a matter of personal choice when to utilize one or the other.
No comments:
Post a Comment
its cool