CSS - Selectors


CSS - Selectors

  • A selector is an HTML element at which a CSS styles will be applied. This could be any element tag like <h1>, <p> or <table> etc.

Types of Selectors in CSS :

  • Element Selectors
  • Id Selectors
  • Class Selectors
  • Descendant Selectors
  • Universal Selectors
  • Grouping Selector
  • Attribute Selector

Element Selector :

  • The element selector selects elements based on the element name. 

Example :

p {  
	text-align: center; 
	color: red;
}

Id Selector :

  • The id selector is used to specify a style for a single, unique element.
  • Id selector is represented by ‘#’ symbol followed by the id name.

Example :

#para1 {
        text-align: center;
        color: red;
    }

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 for several elements.
  • Class selector is represented by ‘.’ symbol.

Example :

.center {
            text-align: center;
color: red; }


Descendant Selector :

  • Apply a style guideline to a specific component just when it lies inside a specific component.

Example :

  • style rule will apply to <li> element only when it lies inside <ol> tag.
ol li { 
    list-style-type: disc; 
}


Universal Selector :

  • Selecting elements of a specific type, the universal selector quite simply matches the name of any element type.
  • To select elements with a specific attribute, write a asterisk (*) character.

Example :

* { 
        color: #000000; 
    }


Grouping Selector :

  • Apply a style to many selectors. Just separate the selectors with a comma and type the elements.

Example :

h1, h2, p {
            text-align: center;
         color: red;     }