Table of Contents
CSS Selectors
CSS selectors are used to “find” (or select) the HTML elements you want to style.
CSS selectors are five categories
- Simple selectors
- Combinator selectors
- Pseudo-class selectors
- Pseudo-elements selectors
- Attribute selectors
Simple selectors
- The simple selectors select elements based on name, id, class.
Name simple selector
- The element selector selects HTML elements based on the element name.
id Selector
- The id of an element is unique within a page, so the id selector is used to select one unique element.
- Id selector call the id by hash (#)
Note: An id name cannot start with a number!
Example
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#p {
text-align: center;
background-color: seagreen;
color: white;
font-size: 20px;
}
</style>
</head>
<body>
<h1>This is first heading</h1>
<p id="p">This is paragraph</p>
<h3>This is third heading</h3>
<h2>This is second heading</h2>
<p id="p">This is paragraph</p>
</body>
</html>
CSS class Selector
- The class selector selects HTML elements with a specific class attribute.
- Class selector call the id by Dot (.)
Note: An id name cannot start with a number!
Example
<!DOCTYPE html>
<html>
<head>
<style>
.demo{
text-align: center;
background-color: green;
color: white;
font-size: 50px;
}
</style>
</head>
<body>
<h1>This is first heading</h1>
<p class="demo">This is paragraph</p>
<h2>This is second heading</h2>
<h3 class="demo">This is third heading</h3>
</body>
</html>
Universal Selector
- The universal selector (*) selects all HTML elements on the page.
Example
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
*{text-align: center;
background-color: seagreen;
color: white;
font-size: 20px;
}
</style>
</head>
<body>
<h1>This is first heading</h1>
<p>This is paragraph</p>
<h3>This is third heading</h3>
<h2>This is second heading</h2>
</body>
</html>
Grouping Selector
- The grouping selector selects all the HTML elements with the same style definitions like the h1, h2, and p elements have the same style definitions. To group selectors, separate each selector with a comma.
Example
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
h1,h3{
text-align: center;font-size: 50px;
color: white;background-color: rgb(11, 85, 244);
}
h2,p{
text-align: right; color: green;
font-size: xx-large;background-color: red;
}
</style>
</head>
<body>
<h1>This is a first heading</h1>
<p>This is a paragraph</p>
<h3>This is a third heading</h3>
<h2>This is a second heading</h2>
</body>
</html>