2

Some CSS selectors have # in front of them, what does that mean?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Bin Chen
  • 61,507
  • 53
  • 142
  • 183

5 Answers5

18

It's the ID selector, a fundamental feature of the CSS standard. It matches the HTML element with the given ID, according to the id attribute (assuming a conforming document, of course). See the W3C Selectors spec for more.

<!DOCTYPE html>
<html lang="en">

<head>
  <style type="text/css">
  #my-div {
      color: #f00;
  }
  </style>
</head>

<body>
  <div id="my-div">This text will be red.</div>
  <div id="another-div">This text will not be red.</div>
</body>

</html>

You may also have seen the # notation used in a URL fragment identifier to refer to named anchors (<a name="some-anchor"></a>). These can also point to elements with certain IDs in your page, just like named anchors, and I gather that it's why CSS uses the same notation for selecting IDs.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 5
    I'll just leave this here. http://meta.stackexchange.com/questions/120025/will-i-be-downvoted-for-giving-a-w3schools-link – BoltClock Jan 23 '12 at 21:48
  • 1
    Dont forget the "Element" vs "Class" in CSS. An "Element" `#myElement` should only be used once per page, where a class `.myClass` can be used multiple times. – Chase Florell Jan 23 '12 at 21:57
3

The selector, #foo will match any element with an ID attribute with a value of "foo".

<style type='text/css'>
#foo { color: red; }
</style>

<div id='foo'>red text</div>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
2

It selects based on the id of html element...

http://www.w3.org/TR/CSS2/selector.html#id-selectors

<style>
#myDiv { }
</style>

<div id="myDiv">
</div>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
JeremyWeir
  • 24,118
  • 10
  • 92
  • 107
2

In CSS,

# is Mention for ID Selector

. is Mention for Class Selector

Karthik
  • 3,221
  • 5
  • 28
  • 38
2

You might also have seen something like

div#myDiv {}

Which means "a DIV-tag with ID set to 'myDiv'"

sewa
  • 1,894
  • 1
  • 13
  • 8