CSS Selectors


Go to main Page

Selectors in CSS

Selectors are used to selecting the element from HTML to style it.

In CSS selectors are distributed in five categories:

  1. Simple Selectors are based on name, id, and class.
  2. Attribute Selectors choose elements which depends upon attribute.
  3. Pseudo-class Selectors selects element which is based on certain state.
  4. Pseudo-elements Selectors choose part of an element.
  5. Combinator Selectors select the elements which are based on certain relation b/w them.

CSS element selector

Element selector choose the HTML elements which depends upon element name.


Example


<p>Paragraph two</p>
    <p>paragraph</p>
<style>
p{
color:red;
text-align:center;

}
</style>


Explaination

In the style tag, we are styling the paragraph by its element name.


What is CSS id selector

The id selector use the id attribute with (#) sign to select the elements

Example


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
<style>
    #heading1{
        color:red;
        font-size: 50px;
        text-align: center;
    }
    #heading2{
        color:orange;
        font-size: 50px;
        text-align: center;
    }
</style>
</head>
<body>
    <h1 id="heading1">Heading</h1>

    <h1 id="heading2">Heading</h1>
</body>
</html>
  


What is CSS class selector?

The class selector use the class attribute with (.) sign to select the elements

Example


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
<style>
    .heading1{
        color:red;
        font-size: 50px;
        text-align: center;
    }
</style>
</head>
<body>
    <h1 class="heading1">Heading</h1>
</body>
</html>
  


What is Universal selector?

The Universal selector selects the complete HTML page with * sign.


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
<style>
    *{
        color:red;
        font-size: 50px;
        text-align: center;
    }
</style>
</head>
<body>
    <h1 >Heading</h1>
    <h1 >Topic</h1>
    <h1 >Hack</h1>
</body>
</html>