What is Selector in CSS?
A simple definition of a CSS selector is to define HTML elements you want to style with CSS.
There are many different types of CSS selectors, each with its own unique syntax, before going to discuss their types, let's know how to use Selector.
How to Use Selector in CSS
There are majorly two ways that you can use selectors in CSS. Firstly, If you have your HTML and CSS in one doc, then you simply have to add CSS selectors into the section of your webpage.
Secondly, you can also keep your HTML and CSS in separate documents. In that case, you might have an HTML document labeled index.html and a CSS file labeled style.css. The index.html file must include a line of code referencing the CSS file so that those styles are rendered on your webpage.
You will see this method example below...
< !DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">D
<title>CSS Selector</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Get Started with css selector</h1>
</body>
</html>
Have you notice <link rel="stylesheet" href="style.css"> line!
that line is the reference to your CSS file. That file would only include the selector blocks you’ll see below and other custom CSS.
Let's get a deep dive into Selector types
Types of CSS Selectors
Here, we cover major four types of CSS selectors that can help you to select different group elements.
We first go through the largest group of elements and then move to smaller ones accordingly.
Universal Selector
The asterisk (*) is known as the CSS universal selectors. It can select whole the HTML page with all types of elements. The asterisk can also be followed by a selector while used to select a child object. This selector is useful when we want to select all the elements on the page.
* {
margin: 0;
padding: 0;
text-align: center;
}
Element Selector
The element selector selects HTML elements based on the element name (or tag) i.e p, h(1-6), div, span, etc. These <h1>, <span>tags are use in CSS as an Element Selector.
h1 {
background: red;
color: white;
}
Here’s the result:
Class Selector
The class selector is a way to select all of the elements with the specified class name belonging to a particular attribute and apply styles to each of the matching elements. This selector must start with ( . ) and then the class name.
.select{
font-size: 12px;
background: springgreen;
color:#130e0e;
}
Here’s the result:
ID Selector
The Id selector is a way to select only the element with the specified id and apply styles to that element. It is unique on a page and can only apply to at most one element. To use an Id selector in CSS, you simply write a hashtag (#) followed by the ID of the element.
#selector{
color: black;
background: yellow;
font-family: Arial, Helvetica, sans-serif;
}
Here’s the result:
Guidance from Hitesh Choudhary