Difference between Class and ID selectors?

Discussion in 'CSS' started by Grand, Dec 29, 2006.

  1. #1
    I can't seem to work out how they are different. Probably a stupid question, but hey, I'm a stupid sort of person.

    Thanks.
     
    Grand, Dec 29, 2006 IP
  2. Cypherus

    Cypherus Peon

    Messages:
    1,551
    Likes Received:
    102
    Best Answers:
    0
    Trophy Points:
    0
    #2
    In the CSS, a class selector is a name preceded by a full stop (.) and an ID selector is a name preceded by a hash character (#).

    The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.

    You can also apply a selector to a specific HTML element by simply stating the HTML selector first, so p.jam { whatever } will only be applied to paragraph elements that have the class 'jam'.
     
    Cypherus, Dec 29, 2006 IP
  3. tonyrocks

    tonyrocks Active Member

    Messages:
    1,574
    Likes Received:
    50
    Best Answers:
    0
    Trophy Points:
    88
    #3
    Think of a Class as being able to describe an object, where as an ID is describing a specific object.

    For instance, an SUV is a Class of Automobiles...so is Truck, however a Toyota Tundra identifies a truck name. So when telling someone you want a red Toyota Tundra, then you use ID. But when you tell someone you like red automobiles then you use CLASS. Lord I was born a RAMBLING man...
     
    tonyrocks, Dec 29, 2006 IP
  4. Grand

    Grand Peon

    Messages:
    165
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You know what, I almost get that! Thanks!

    So, let's see if I've got this right...

    Say I have a class with no tag such as:

    .lookscool { something cool }

    I could have <h1 class="lookscool"> and <p class="lookscool">
    Whereas with ID, it can only be <h1> OR <p> or whatever else.

    So is

    p.lookscool { coolness }
    <p class="lookscool">

    and

    #lookscool { coolness }
    <p id="lookscool">

    the same thing?

    And you can't go:
    #lookscool { coolness }
    <p id="lookscool">
    <h1 id="lookscool">
    right?

    Ok, I hope I've got that right, thanks.
     
    Grand, Dec 29, 2006 IP
  5. Dan Schulz

    Dan Schulz Peon

    Messages:
    6,032
    Likes Received:
    437
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Yup. An ID value can only be used once on a page (example: <div id="myID"></div> and <div id="yourID"></div> are legal, but having two elements, whether a pair of DIVs or a DIV and a P, or even a P and a SPAN with id="myID" are not), but a class can be used over and over.

    As with the second part of the previous example (<div id="myID"></div> and <div id="myID">) replace the ID with class and you're golden.
     
    Dan Schulz, Dec 29, 2006 IP