CSS selectors allow you to select and manipulate HTML elements based on the following options:
The element selector selects HTML elements based on their element name. For example, you can select all <p> tag/elements on a page shown in the below example:
Example 1: To Style all paragraph with centered align and red color.
<html>
<head>
<style>
p{
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<h2>Heading 2</h2>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
<html>
An ID selector uses the ID attribute to style a particular HTML element. An ID should be unique within an HTML page, So, the ID selector is used to select only a single element. An ID Selector starts with the hash (#) symbol, followed by an ID name, and then style definition.
The style rule below will be applied to the HTML element with id="para1":
Example 2: use of ID Selector
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<p id="para1">Paragraph 1</p>
<p>Paragraph 2</p>
<h2>Heading 2</h2>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
<html>
Class Selector is useful when you want to apply formatting on different HTML elements with the same style. The class selector starts with a dot(.) character followed by the class name, and then style definition.
Example 3: All HTML elements with class="center" will be center-aligned:
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class="center">Heading 1</h1>
<p class="center">Paragraph 1</p>
<p>Paragraph 2</p>
<h2>Heading 2</h2>
<p class="center">Paragraph 1</p>
<p class="center">Paragraph 2</p>
</body>
<html>
Example 4: All <p> elements with class="center" will be center-aligned.
<html>
<head>
<style>
p.center {
text-align: center;
color: red;
}
h1.center {
color: green;
}
</style>
</head>
<body>
<h1 class="center">Heading 1</h1>
<p class="center">Paragraph 1</p>
<p>Paragraph 2</p>
<h2>Heading 2</h2>
<p class="center">Paragraph 1</p>
<p class="center">Paragraph 2</p>
</body>
<html>
Class selector are usually given to groups of elements instances sharing some a common style, whereas ID is used to identify one specific instance of an element.
Grouping technique is useful when you are using the same style to different HTML tags.
"Without grouping, the syntax would be":
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
It can be grouped, to minimize the code. To group selectors, separate each selector with a comma.
h1, h2, p {
text-align: center;
color: red;
}