CSS Selectors are used to selecting a particular HTML element you want to style. There are several different types of selectors in CSS.
In this CSS section, we will be learning CSS selectors.
- CSS Element Selector
- CSS Id Selector
- CSS Class Selector
- CSS Universal Selector
- CSS Group Selector
CSS element selector:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
text-align: center;
}
h1 {
color:green;
text-align: center;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This paragraph is styled with CSS.</p>
</body>
</html>
CSS ID Selector
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#heading{
color: green;
text-align: center;
}
#paragraph{
color: red;
text-align: center;
}
</style>
</head>
<body>
<h1 id="heading">Hello World!</h1>
<p id="paragraph">This paragraph is styled with CSS.</p>
</body>
</html>
CSS Class Selector
<!DOCTYPE html>
<html>
<head>
<style>
.paragraph{
color: red;
text-align: center;
}
</style>
</head>
<body>
<h1 id="heading">Hello World!</h1>
<p class="paragraph">This paragraph is styled with CSS.</p>
<p class="paragraph">It is very easy and simple.</p>
</body>
</html>
CSS universal selector
<!DOCTYPE html>
<html>
<head>
<style>
*{
color: green;
text-align: center;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This paragraph is styled with CSS.</p>
</body>
</html>
CSS Group Selector
here is a CSS code without a group selector
h1 {
text-align: center;
color: blue;
}
h2 {
text-align: center;
color: blue;
}
p {
text-align: center;
color: blue;
}
as we see, you need to define CSS properties for all the elements.
h1,h2,p {
text-align: center;
color: blue;
}
Full example:
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello rathorji.in</h1>
<h2>Hello rathorji.in (In smaller font)</h2>
<p>This is a paragraph.</p>
</body>
</html>
May this example help you.