What's the difference between . and # in a css file?

Viewed 17898

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?

4 Answers

. 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 could be 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.)

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.

. 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.

Related