Selectors in CSS

What are CSS Selectors?

  • CSS selectors are used to select the HTML elements for styling.

  • There are multiple types of selectors in CSS: element selector, group selector, id selector, class selector, etc.

  • Today we will see only some basic selectors in CSS and other selectors we will learn in upcoming tutorials.


Element Selector:

Element selectors are used to targeting the HTML element by tag name and style them in our style sheet.

Example:

index.html

<!DOCTYPE html>
<html>
<head>
    <title> Element Selectors </title>
    <link rel="shortcut icon" href="favicon.png">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <p> This is a paragraph </p>
</body>
</html>

style.css

p{
    color: purple;
}

Output:


Group Selectors

As the name suggests group selectors are used to selecting multiple elements and applying the same style to them.

Example:

index.html

<!DOCTYPE html>
<html>
<head>
    <title> Group Selectors </title>
    <link rel="stylesheet" href="style.css">
    <link rel="shortcut icon" href="favicon.png">
</head>
<body>
    <h3> This is a heading </h3>
    <p> This is a paragraph </p>
</body>
</html>

style.css

h3, p{
    color: red;
}

Output:


Id Selector

  • Id selectors are mainly used to target particular HTML element with the help of id and apply styles to them. The id of any HTML element should be unique.

  • Hash (#) is used to target the particular element from the HTML document.

Example:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title> Id Selector </title>
    <link rel="stylesheet" href="style.css">
    <link rel="shortcut icon" href="favicon.png">
</head>
<body>
    <h2 id="heading"> This is heading </h2>
</body>
</html>

style.css

#heading {
    color: blue;
}

Output:


Class Selector

  • Class selectors are mainly used to target multiple HTML elements with their classes and apply styles to them. An HTML element can contain multiple classes and multiple elements can have the same class.

  • (.) is used to target the multiple elements with the class from the HTML document.

Example:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title> Id Selector </title>
    <link rel="stylesheet" href="style.css">
    <link rel="shortcut icon" href="favicon.png">
</head>
<body>
    <p class="para"> This is first paragraph </p>
    <p class="para"> This is second paragraph </p>
    <p class="para"> This is third paragraph </p>
</body>
</html>

style.css

.para {
    color: purple;
}

Output:



Selectors in CSS Part-3 PDF

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad