CSS Selectors

CSS selectors are used to select a particular HTML element or a group of elements, so that we can apply style on it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Types of selector</title>
  </head>
  <body>
  <div class="heading">
<nav>
<ul>
        <li></li>
        <li id="two"></li>
        <li></li>
</ul>
</nav>
</div class="body">
    <p>This is a static template, there is no bundler or bundling involved!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </body>
</html>

Types of selectors are as follows:

1. Universal selector It is denoted by an asterisk, it is used to select whole HTML document. example:

*{
  color:  #ffffff;
}

2.Individual selector It is used to select a particular tag by calling that tag name. example: to select

just type as follows,

div{
font-size: 18px;
}

3. Class and Id selector Suppose a tag is having a certain class or may be Id in that case we can also target that tag or may be group of tags with same class name by selecting its class name and id name but remember id should be unique for every tag. An id can be selected with '#' sign and class can be selected with '.' (dot). example:

.heading{
  background-color: #1f1f1f;
}

and, for targeting an ID

#two{
  font-size: 12px;
}

4.Chained Selector It is used to select or target child tag which is encapsulated by the parent tags. There can be nested parents as well. If we have to target the

  • tags we can do so by this,
  • div ul li {
    font-family: 'sans';
    }
    

    5.Combined selector Suppose we want to apply same kind of style to two different tags or may be more than two different tangs , so in that case we can use combined selector. It will select those element at the same time apply all the styling. Example: We want to apply color #1f1f1f to div tag as well as p tag so,

    div, p{
    color: #1f1f1f;
    }
    

    6.Direct child selector From the example, if we want to select the second child of ul which is again child of div we can use direct child selector as follows:

    div>ul>#two{
    font-size: 30px;
    }
    

    7.Sibling Selector There are two types of sibling selector which are as follows: So if we want to select an element which is just after any other tag but having the same parent tag we can use "+". Example:

    img + p{
    background-color: blue;
    }
    

    And, if we want to select the next sibling of any specified element having same parent element can be done as:

    img ~ p{
    background-color: yellow;
    }