In CSS what is the difference between "." and "#" when declaring a set of styles? [duplicate]
What is the difference between #
and .
when declaring a set of styles for an element and what are the semantics that come into play when deciding which one to use?
Yes, they are different...
#
is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:
-
#foo {}
will style the single element declared with an attributeid="foo"
-
.foo {}
will style all elements with an attributeclass="foo"
(you can have multiple classes assigned to an element too, just separate them with spaces, e.g.class="foo bar"
)
Typical uses
Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.
Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {}
which would only apply to <h1 class="error">
Specificity
Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box">
any rules for #sidebar
with override conflicting rules for .box
Learn more about CSS selectors
See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.
EDIT: Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.
The #
means that it matches the id
of an element. The .
signifies the class name:
<div id="myRedText">This will be red.</div>
<div class="blueText">this will be blue.</div>
#myRedText {
color: red;
}
.blueText {
color: blue;
}
Note that in a HTML document, the id attribute must be unique, so if you have more than one element needing a specific style, you should use a class name.