CSS Selectors

In addition to setting a style for a HTML element, CSS allows you to specify your own selectors called "id" and "class".

The class Selector

  • The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
  • This allows you to set a particular style for many HTML elements with the same class.
  • The class selector uses the HTML class attribute, and is defined with a "."
  • In the example below, all HTML elements with class="center" will be center-aligned:
  • Example
    .center {text-align:center;}
  • You can also specify that only specific HTML elements should be affected by a class.
  • In the example below, all p elements with class="center" will be center-aligned:
  • Example
    p.center {text-align:center;}

The id Selector

  • The id selector is used to specify a style for a single, unique element.
  • The id selector uses the id attribute of the HTML element, and is defined with a "#".
  • The style rule below will be applied to the element with id="paragraph":
  • Example
    #paragraph
    {
    text-align:center;
    color:red;
    }

The Type Selectors

  • This is the same selector we have seen above. Again one more example to give a color to all level 1 headings
  • h1 { 
       color: #36CFFF; 
    }

The Universal Selectors

  • Rather than selecting elements of a specific type, the universal selector quite simply matches the name of any element type
  • * { 
      color: #000000; 
    }
  • This rule renders the content of every element in our document in black.

The Descendant Selectors

  • Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, style rule will apply to <em> element only when it lies inside <ul> tag.
  • ul em {
      color: #000000; 
    }