The CSS Id Selector

How do we specify an id selector?

  • Id selectors let you assign styles in a way that is independent of document elements. These selectors can be used on their own or in conjunction with type selector.
  • Id selectors are written in a similar way to class selectors, except you use a # (hash symbol) to indicate them instead of the class's . (period).
  • You use id selectors in your web pages by giving the id attribute for the appropriate html elements the name of the id selector.
    #idName {color:red; font-size:12px; line-height:15px;}
    /* For a id selector that is independent of document elements
    you only start with a # and then the name of the id.*/
    elementName#idName {color:red; font-size:12px; line-height:15px;}
    /* If you would like the id selector to be
    related to an html element you need to provide the name of html element,
    followed by a # and then the name of the id selector.*/
    A class selector example:
    <html>
      <head>
        <style type="text/css">
          p { color: green;}
          p#warning {font-size: 16pt; color: blue; }
        </style>
      </head>
      <body>
        <p>This paragraph has no id selector, but a type selector</p>
        <div >
          Text inside the div follows the defaults.
          <p id='warning'>paragraph inside div element is now blue and 16 pt.</p>
         </div>
      </body>
    </html>
    Of course, you can create a descendant selector or a child selector that is a mix of a id selector and a type selector.
    div p#myid {color:red; font-size:12px;}
    With this CSS rule in effect, any HTML code containing an p element with attribute id='myclass' inside an div element on the web page is automatically rendered in 12-pixel font-size type and colored red.
    div>p#myid {color:red; font-size:12px;}
    With this CSS rule in effect, any HTML code containing an p element with attribute id='myclass' as direct child element inside an div element on the web page is automatically rendered in 12-pixel font-size type and colored red.

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.