Reputation: 395
I'm learning in CSS, I am really confused when to use .
(dot) and when to use #
in CSS file. Sometimes I really wondered which one I should use.
Upvotes: 1
Views: 168
Reputation: 268374
While there are many humans, there is only one you. As such, .
is for classes, which can appear over and over in a document. #
is for IDs, which are unique to a document.
<div class="firstname" id="personA">
<p class="lastname">Sampson</p>
</div>
<div class="firstname" id="personB">
<p class="lastname">Sampson</p>
</div>
Note the unique identifier for both div
, personA
and personB
. However both elements have classes in common, such as .firstname
, and .lastname
.
You can see how these are used out in the wild by looking at tools like Modernizr. This feature-detection tool assists you by adding classes to the <html>
element that inform you as to what the device or browser is capable of:
<html lang="en" dir="ltr"
id="modernizrcom"
class="js no-touch postmessage history multiplebgs boxshadow...">
Here we see the one unique value for the <html>
element, #modernizrcom
. Following, a series of classes that give more general info about the element. This is a clear example of how an element can have only one id, but many classes.
Because these values are completely unique, they can cause you to paint yourself into a corner at times. It's worth reading Disallow IDs in Selectors to know more about the potential issues with using IDs in your selectors.
Upvotes: 8
Reputation: 2670
. is represent class
# is represent ID(but used only once in a page)
always the id is having the first priority in the race.
ex:
in the style
.alignmeleft{float:left;}
#alignmeright{float:right;}
in the html:
<div class="alignmeleft" id="alignmeright">
<!--div content-->
</div>
OUTPUT
THE DIV WILL ALIGNED RIGHSIDE
Upvotes: 0
Reputation: 7385
a dot (.) represents a class, a hash (#) represents an id.
There is more to it, but this is the gist:
An id (#myID) should be used when you only intend to use that selector once
A class (.myClass) should be used to create a reusable piece of styling code (e.g. to make text blue)
Upvotes: 0
Reputation: 122376
The # is used for the id of an element and . is used for classes of an element. In a HTML document, an id is unique (there should only be one element with that id) while classes can occur multiple times.
<div id="content" class="shade light">
</div>
You can now do:
#content { border: solid 1px black; }
to add styling to that particular div element. But you can also do:
.light { background-color: #eeeeee; }
The difference is that the latter will apply that background color to all elements with that class (i.e., all elements with the class light
while the first CSS statement will only add styling to the element with the id content
).
Upvotes: 3