- What is a selector in CSS?
In CSS, selectors are used to specify the HTML elements on our web pages that we want to style. A wide variety of CSS options are available to allow great precision in selecting style elements. In this article we will discuss each type in more detail:
Types of Selectors
There are various types of selectors in CSS. They are:
- Element Selector
- Id Selector
- Class Selector
- Universal Selector
- Group Selector
Element Selector:
An element type selector matches all instance of the element in the document with the corresponding element type name.
The style rules inside the p selector will be applied on every
element (or paragraph) in the document and color it blue, regardless of their position in the document tree.
Id Selector:
An id selector is defined by a hash sign (#) immediately followed by the value of the id.This style rule renders the text of an element in red, whose id attribute is set to error.
Class Selector: Any HTML element that has a class attribute can be selected using class selectors. The element with that class will be formatted according to the defined rule. A period sign (.) immediately follows the class value defines the class selector.
Universal Selector:
An asterisk (*) marks the universal selector, which matches all elements on the page. It is possible to omit the universal selector if other conditions are met on the element. For quick testing purposes, this selector is often used to remove the default margins and paddings.
Group Selector:
The grouping selector is used to select all the elements with the same style definitions. Grouping selector is used to minimize the code. Commas are used to separate each selector in grouping.
Pseudo Selectors:
pseudo-classes A CSS pseudo-class is a keyword added to a selector and defines a special state of the selected elements. Syntax: elem:pseudo-class { style properties } This selector is represented by a colon (:)
<h1>Shopping list</h1>
<ul>
<li>Milk</li>
<li>Butter</li>
<li>Eggs</li>
<li>Sugar</li>
</ul>
li:hover {
background-color: black;
color: white;
}
In this example, we're applying a black background color and a white text color to every
OutPut:
Some of the most common CSS pseudo-classes are:
:active, :hover, :focus, :disabled, :checked, :first-child, :nth-child, :first-of-type.
pseudo element
A CSS pseudo-element is a keyword added to a selector to style a specific part of the selected elements. Syntax: elem:pseudo-element { style properties } This selector is represented by a colon (::)
<p>CODE</p>
p::before{
content: "_";
}
In this example, we're appending an underscore symbol in front of every
element.
Output:
Some of the most common CSS pseudo-elements are:
::after (can also be written as :after), ::before (can also be written as :before), ::marker, ::placeholder, ::first-letter.