Welcome to WebmasterWorld Guest from 54.166.191.159

Forum Moderators: not2easy

Message Too Old, No Replies

CSS: ID versus CLASS attributes

what is the difference?

     
7:32 pm on Mar 25, 2003 (gmt 0)

10+ Year Member



I'm trying to figure out the "rules" for when I should use the ID attribute versus the CLASS attribute when setting styles for my HTML tags. I know ID is for handy reference in scripting, but it can also be used to apply styles. I know CLASS is used to apply styles. But can someone please tell me when it's better to use one versus the other?
7:39 pm on Mar 25, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to Webmaster World!

An id can only be used once per page. So, use id for main layout elements that you only use once per page and class for elements that will use the class more than once.

#topbanner{}
#left{}
#main{}
#right{}

7:43 pm on Mar 25, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Check out Nicks CSS Crash Course [webmasterworld.com] for some good reading.
7:53 pm on Mar 25, 2003 (gmt 0)

10+ Year Member



that's great! thank you.
5:58 am on Mar 27, 2003 (gmt 0)

5+ Year Member



Best way to think about it:
id
can be the target for a hyperlink. So you can do
<p id="foo">

instead of
<p><a name="foo"></a>

and link to it with an
<a href="/this/page#foo">

Not only is the former sematically cleaner, it is required in xhtml 1.1, where the
name
attribute has been dropped.

So an

id
must be unique on a page, and should carry some semantic meaning (ie, as something you might conceivably link to). A
class
is more generic, denoting a set of element of the "same" sort.
7:28 am on Mar 27, 2003 (gmt 0)

WebmasterWorld Senior Member drdoc is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Welcome [webmasterworld.com] to Webmaster World, professor! ;)

To further clearify your excellent explanation: just think about the names...

ID = identifier... class = group...

Every person has some form of unique ID, a drivers licence or passport or whatever, and it works the same way on Web pages.

ID = unique
class = group, no matter if there's one or a few thousand elements in the group

7:59 pm on Mar 27, 2003 (gmt 0)

10+ Year Member



in that case, what would be the point of ever assigning styles to elements via the ID attribute? wouldn't it make more sense to always set styles with a class declaration and just to use ID for identifying?
8:06 pm on Mar 27, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You also may apply a class to a bunch of items, but need to slightly modify a few of them based on their id, in those cases you use both referencing techniques.

ie.

.container {
border:thin black groove;
font-size:80%;
}

#left {
position:absolute;
top:0;
left:0;
width:20em;
}
#main {
top:0;
left:20em;
}

 

Featured Threads

Hot Threads This Week

Hot Threads This Month