CSS Selector
CSS selectors are used to choose the elements you want to style. They are
part of a CSS rule set and allow you to target HTML elements based on
their id, class, type, or attributes.
There are various types of selectors in CSS:
- CSS Element Selector
- CSS ID Selector
- CSS Class Selector
- CSS Universal Selector
- CSS Group Selector
CSS Element Selector
He element selector targets HTML elements based on their tag name.
Example
<!DOCTYPE html>
<html>
<head>
<style>
h1{
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Heading</h1>
<h1 id="ak">Me too! And me!</h1>
</body>
</html>
Output
CSS ID Selector
- The id selector targets a specific HTML element by its unique id attribute.
- Since each id is unique on the page, it is used to select a single, specific element.
- It is written with a hash symbol (#) followed by the element's id.
Example
<!DOCTYPE html>
<html>
<head>
<style>
#ak{
color: red;
}
</style>
</head>
<body>
<h1>Heading</h1>
<h1 id="ak">Me too! And me!</h1>
</body>
</html>
Output
CSS Class Selector
The class selector targets HTML elements that have a specific class
attribute. It is written with a period (.) followed by the class name.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.ak{
color: red;
}
</style>
</head>
<body>
<h1 class="ak">Heading</h1>
<p>paragraph.</p>
</body>
</html>
Output
CSS Universal Selector
The universal selector acts as a wildcard, selecting all elements on the
page.
Example
<!DOCTYPE html>
<html>
<head>
<style>
*{
text-align: center;
color: red;
}
</style>
</head>
<body>
<h2>Heading</h2>
<p>This style will be applied to every paragraph.</p>
<p>Me too!</p>
<p>And me!</p>
</body>
</html>
Output
CSS Group Selector
The grouping selector applies the same styles to multiple elements. It
helps reduce code by combining selectors with commas.
The CSS code without using the group selector:
h2{
text-align: center;
color: red;
}
h1{
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
The CSS code using the group selector
h2,h1,p{
text-align: center;
color: red;
}
Example
<!DOCTYPE html>
<html>
<head>
<style>
h2,h1,p{
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>This style will be applied to every paragraph.</h1>
<h2>Me too!</h2>
<p>And me!</p>
</body>
</html>