tags:

views:

192

answers:

4

In css examples, I've seen rules defined starting with a . and some starting with # - sometimes these are mixed in the same file. What is the difference between these rules:

h1  { font-size:18pt;}
.new-alerts  { font-size:11pt; font-weight:bold;}
#old-alerts  { position:relative; font-size:10pt; }

Are they referenced differently on the html page? Is it how the properties are inherited?

+18  A: 

. refers to a class. <span class="one" /> could be selected with .one.

# refers to an ID. <span id="one" /> could be selected with #one.

You should be using classes when there is more than one of a given element, and IDs when you know there will only be one. #navigation-bar would be using an ID because you will only have one navigation bar in your layout, but .navigation-link would be using a class name because you will have multiple navigation links. (It'd be better practice to use #navigation-bar a:link to get the navigation links, but you get my point.)

Matchu
What does that mean? How are they different?
George
They're both ways to semantically add information to an element. While you can only mark one element with a particular `id`, you can have many with the same `class`.
John Feminella
You use ID's for one specific tag, it's unique and you should only have one of the same ID on a page. Classes are re-usable and can be applied to as many elements as you want.
Shawn Steward
First added basic answer, then went back to add explanation.
Matchu
However, `.navigation-link` might also be replaced by `#navigation-bar a:link` which refers to a link within the navigation bar. Note that elements itself have semantic meaning most of the time and you can save yourself the use of too many classes if you use them properly.
Joey
@Johannes Rössel: Note added :)
Matchu
Another consideration to make when deciding whether to use a class or an id is that with ids you can direct users directly to the content by putting the id in the URL, aka an "anchor". http://www.example.com/index.html#about_us would go to that id in the content of the page.
Ben
+6  A: 

The dot . is a class selector, the hash/pound/octothorpe # selects by an ID:

<style>
    .foo { ... }
    #bar { ... }
</style>
...
<p class='foo'>Foo</p>
<p id='bar' class='baz'>Bar</p>

IDs have to be unique throughout a document, classes don't have to be. That's basically the primary difference. There are some things to note with regard to scripting but those are usually not of particular interest when styling.

Furthermore, an element may belong to multiple classes:

<p class="foo bar baz">

and as seen above, classes and IDs are not mutually exclusive.

Joey
+1  A: 

See Class vs ID

Sarfraz
+2  A: 

. is a class and can be reused many times and for different elements

# is an ID and must be used only once on each page.

Shaun