CSS Selectors

In this tutorial we will learn about CSS selector. CSS Selectors are use to select and style HTML elements. There are various ways to select and style HTML elements you can select HTML elements with tag name. For example you want to style H1 tag in your web page when you with style (like you change text color to RED) it using tag name all the h1 elements in your web page will automatically adopt that style. Furthermore there are various other ways to select HTML elements with we will discuss in this tutorial. Ways to select HTML elements.

  • Based on Tag Name
  • Based on Class
  • Based on ID
  • Universal Selector

Based on Tag Name: 

This type of selector work on similar kind of elements. For example if you change color of h4 element using this selector it will change color of all h4 elements in web page(in case of internal CSS). check this example below.

<html>
     <head>
        <style>
          h4{
           color:red
            }
       </style>
     </head>
     <body>
        <h4>This is H4 Tag</h4>
        <h4>This is H4 Tag</h4>
        <h4>This is H4 Tag</h4>
    </body>
</html>

Based on Class:

To use class selector we use special class attribute with HTML elements. With the help of class selector we can select specific HTML element at single time. For example you have total five h3 elements in web page you want to change color of first and last h3 element we can do this with the help of class selector. To mention class selector we write . followed by class name in CSS. Check this example.

<html>
     <head>
        <style>
          .heading{
           color:red
            }
       </style>
     </head>
     <body>
        <h4 class="heading">This is H4 Tag</h4>
        <h4>This is H4 Tag</h4>
        <h4 class="heading">This is H4 Tag</h4>
    </body>
</html>

Based on ID:

To use id selector we use id attribute with HTML element. Id selector is use for a specific element in web page. To mention id selector we write # followed by id name in CSS. Check the following example.

<html>
     <head>
        <style>
          #mainHeading{
            color:red
            font-size:28px;
            }
       </style>
     </head>
     <body>
        <h4 id=" #mainHeading">This is H4 Tag</h4>
        <h4>This is H4 Tag</h4>
        <h4>This is H4 Tag</h4>
    </body>
</html>

Universal Selector:

This universal selector effects every element of Web page. To mention universal selector we write * in CSS file. Check this Example.

<html>
     <head>
        <style>
          *{
            color:red
            font-size:15px;
            }
       </style>
     </head>
     <body>
        <h4>This is H4 Tag</h4>
        <h5>This is H4 Tag</h5>
        <h6>This is H4 Tag</h6>
    </body>
</html>
Spread the love