CSS Selectors

CSS Selectors

CSS Selectors

  • CSS Selector is used to select an HTML element to apply CSS on it.
  • There are different types of CSS selectors.Let's see some of them:

Different Types of Selectors

  • CSS Class selector

    The class selector selects HTML element with a specific class attribute. To select specific class , put a dot operator, followed by the class name.

    If we want to select h1 with class and change the color of it.

  HTML
<h1 class = "heading">Hello</h1>

  CSS
.heading{
    color:red;
}
  • CSS Id Selector

    The ID Selector selects HTML element with specific ID . To select specific
    id , put a hash operator, followed by the id name.

    If we want to select paragraph with id para and change the color of it.

  HTML
<p id = "para">Hello I am Vivek</h1>

  CSS
#para{
    color:black;
}
  • CSS Element Selector

    The Element Selector selects HTML element .

    If we want to select paragraph with p tag , then directly add element name in CSS

  HTML
<p id = "para">Hello I am Vivek</h1>

  CSS
p{
    color:black;
}
  • Descendant Selector

    The Descendant Selector selects all the elements that are descendant of an element.

    The selector will color the p tag of another also as it is descendant of main, even though we are selecting p element of main..

  HTML
<div id = "main">
    <p>Great</p
    <p>Thanks</p>

   <div id = "another">
       <p>Hello</p>
   </div>

</div>

  CSS
#main p{
    color:black;
}
  • Child Selector

    The Child Selector selects only the child of main id not of the id another.

  HTML
<div id = "main">
    <p>Great</p
    <p>Thanks</p>

   <div id = "another">
       <p>Hello</p>
   </div>

</div>

  CSS
#main > p{
    color:black;
}
  • First and Last Child Selector

    It selects first and last child of a given element. If we have a div with three p tag , it will select first and last child of p.

    HTML
    <div id = "main">
      <p>Great</p
      <p>Thanks</p>
      <p>Hello</>p
    </div>
    
    CSS
    #main  p : first-child{
      color:black;
    }
    #main  p : last-child{
      color:black;
    }
    
  • Dynamic Pseudo Classes

    Special Keywords that go after selector. They are used to target special behavioural states.

    HTML
    <div id = "main">
      <button> Calculate </button
    </div>
    
    CSS
    button : hover{
      color : orange;
    }
    
  • nth Child Selector

    It is used to select nth child of an element.

  HTML
<div id = "main">
      <p>Great</p
    <p>Thanks</p>
    <p>Hello</>p
</div>

  CSS
p :nth-child(2){
    color : orange;
}
  • Universal Selector

    It is mother of all selectors , It is used to target every element..

  CSS
*{
    font-size : 2rem;
}