Welcome to the OzoneAsylum FaqWiki
Frequently Asked Questions
CSS

What is the difference between an ID and a class in CSS? Pages that link to <a href="https://ozoneasylum.com/backlink?for=5534" title="Pages that link to What is the difference between an ID and a class in CSS?" rel="nofollow" >What is the difference between an ID and a class in CSS?\

Well we are glad you asked.

from mobrul:

quote:
The difference is in how you use them within your html.
Let us say you have a div that you would like to have positioned in a certain place. Well, since you wish to define the style of that 1 div, you would use the id.

html = <div id='somethingSpecial'>;sdfjsdlf;sj</div>
css = #somethingSpecial{position:absolute; top:10px; left:25px;}

Of course you could go on to define all sorts of things about that div: background color or image, margins, paddings, borders, etc. ... even define the fonts inside that div with font-family, font-size, color, line-height, etc.

Now, on to classes.
classes are used when you wish to define a style that will apply to many elements on your page.
an example would be...let's say you had a page you wanted 2 columns. One column that would hold content, on the right side of the page, and a series of divs that would hold auxiliary stuff (nav, links, sidenotes, whatever) on the left side of the page. All the divs in that second column (the one on the left) could be given a class and then you define that in the style sheet one time so all divs with that class have the same style.

html =
<div id='nav' class = 'auxillary'>;aldfjdsljfsd</div>
<div id='links' class = 'auxillary'>;aldfjdsljfsd</div>
<div id='sidenote' class = 'auxillary'>;aldfjdsljfsd</div>
<div id='whatever' class = 'auxillary'>;aldfjdsljfsd</div>

css = .auxillary{float:left; clear:left; width:40%}

...and so on.
Like using the id's, you may define all sorts of styles to a class of elements -- positioning, padding, margins, borders, background colors and images, fonts, etc.

So, in short, use id to define styles that will apply to only one very specific element (whether that element is a div, span, anchor, table, paragraph...whatever) and use class to define styles that will apply to a collection of elements.

Another thing is, you can define style for a particular type of element.

css = p{font-family:verdana; font-size:10px; color:#4a4a4a;}

(Notice there is no punctuation in front of the 'p')
That style will apply to all paragraphs in your html, unless you later specifically override this with a class or an id style. You can do that with any type of element (div, span, anchor, table, headings, etc.)



-------------------------
Relevant threads:

some questions on css

class VS id what is the difference

-------------------------
Relevant FAQs:

Can I use more than one/multiple class for an element?

__________________
Emperor

(Added by: Emperor on Sat 25-Jan-2003)

(Edited by: Emperor on Sat 08-Feb-2003)

« BackwardsOnwards »

Show Forum Drop Down Menu