sumit
sumit

Reputation: 11267

What is the difference between starting a block of code in CSS by . [dot] and by # [hash]?

Please answer the following questions for the two CSS example codes given in the end.

  1. What is the difference between the two codes? One is starting with dot and one with hash.
  2. How can I call these styles into HTML? Should I use class="searchwrapper" or should I use id="searchwrapper" ? And why, what is the difference?

Example 1: Starting with #[hash]

#searchwrapper {
    /*some text goes here*/
}

Example 2: Starting with .[dot]

.searchbox {
    /*some text goes here*/
}

Upvotes: 13

Views: 6118

Answers (6)

George Cummins
George Cummins

Reputation: 28906

The Difference:

. specifies a class

# specifies an ID

Class Example:

.myElement {...}

will match

<div class="myElement">

ID Example:

#myElement {...}

will match

<div id="myElement">

Class or ID: How to choose

Only one element may have a particular ID, but multiple elements may share a particular class.

  • If you target one specific element, give that element an ID and use # in your CSS.
  • If you target multiple related elements, give them a class and use . in your CSS.

Upvotes: 24

Jas
Jas

Reputation: 71

'.' is class selector and it can apply on multiple element which have same class

'#' is id selector and only apply on particular one element Id

Upvotes: 1

Qtax
Qtax

Reputation: 33918

These are CSS selectors:

  • #foo means an element with id foo
  • .foo means all element with class foo

See http://www.w3.org/TR/CSS2/selector.html

IDs are unique, so you can only have one element with the same ID. While a class can be the same for many elements (and every element can have several classes).

Upvotes: 6

monsieur_h
monsieur_h

Reputation: 1380

These are CSS selectors:

#foo means an element with id set to foo, it refers to <div id="foo"> .foo means an element with class foo, it refers to <div class="foo">

Plus: you can have several elements with the same class but you can't have more than one with the same ìd`. (Actually you can but it's BAD, and W3C will punish you).

Upvotes: 1

Ovais Khatri
Ovais Khatri

Reputation: 3211

"#" is used if you have assigned id to the document element and "." dot is used if you have used class with the document element.

Id for each element on an document is unique, so if you use # means you want to apply to only that element.

Where as if you use "." dot , it means you want to apply css to the elements whose class attirbute is set to that name which is after dot in css. like ".myClass" so myClass is the class name.

You can you can apply same css on multiple ids by :

#id1,#id2{
//your css
}

Upvotes: 1

sll
sll

Reputation: 62524

  1. [dot] is a class selector, see Id Selectors
  2. # is an id selector, see Class Selectors

Upvotes: 1

Related Questions