In CSS, selectors are used to select the HTML elements that we want to style on web pages. CSS rules can select for elements in many different ways. There are three basic kinds of selectors as follows:
type
: to select HTML elements by element name
class
: to select HTML elements by a specific class
value
id
: to select an HTML element associated with a specific id
value
The type selector selects HTML elements based on the element name.
<html>
<head>
<title>Type Selectors</title>
</head>
<body>
<p>Type selector to select element by its name.</p>
</body>
</html>
p {
color: green;
}
The class selector selects HTML elements with a specific class attribute. To select elements with a specific class, a period (.) character is written, followed by the class name.
<html>
<head>
<title>Type Selectors</title>
</head>
<body>
<div class = "bordered">
The She Coder
</div>
</body>
</html>
.bordered {
border: 5px red;
border-style:dashed;
}
The id selector uses the id attribute of an HTML element to select a specific element .Since the id of an element is unique within a page, the id selector is used to select one unique element. To select an element with a specific id, a hash (#) character, followed by the id of the element is written.
<html>
<head>
<title>Type Selectors</title>
</head>
<body>
<div id = "idselector">
<p>The id selector is used to select a specific element.
</p>
</div>
</body>
</html>
#idselector {
color:blue;
border-color:black;
border-style:solid;
}
The universal selector (*) selects all HTML elements on the page.
<html>
<head>
<title>Type Selectors</title>
</head>
<body>
<h1>Universal Selector</h1>
<p> The universal selector (*) selects all HTML elements on the page.
</p>
</body>
</html>
* { color:blue;
border-color:black;
border-style:solid;
}
The grouping selector selects all the HTML elements with the same style definitions to minimize the code. To group selectors, we separate each selector with a comma.
<html>
<head>
<title>Type Selectors</title>
</head>
<body>
<h1>Universal Selector</h1>
<p> The universal selector (*) selects all HTML elements on the page.
</p>
</body>
</html>
h1,p { color:blue;
font-style:italic;
}
Note: In the case where two (or more) selectors target the same element and property, CSS will select which property to apply based on its importance. id
selectors are the most important, followed by class
selectors, and finally, type
selectors.