CSS Selectors
In this article, Let's know about different types of selectors in CSS.
So first we will know what is selector and how it works in CSS. The selector is the first and most important role in CSS. CSS Selectors target the HTML elements according to their id, class, attribute, etc, and help us to style the webpage according to myself. Without a selector, you can't design your web page.
There are different types of selectors in CSS -
Universal selector :
In CSS, A universal selector is used to select all the elements in an HTML page. The asterisk (*) denotes the universal selector.
Example -
* {
background-color: rgb(124, 26, 3);
color: #fff;
}
Output -
Element Selector :
With the help of an element selector, You can select HTML elements based on the element name.
Example -
body {
padding: 10px;
}
h1 {
font-size: 40px;
text-align: center;
color: rgb(31, 3, 34);
}
Output -
Class Selector :
The CSS class selector selects HTML elements with a specific class attribute. In the CSS, To select elements You can write a period (.) character before the name of the class.
Example -
Id Selector :
An id selector uses the id attribute of an HTML element to select the element. An id is always unique within the page so it is chosen to select a single, unique element. In the CSS, To select elements You can write a hash (#) character before the name of the id.
Example -
Group Selector :
This selector is used to style all comma-separated elements with the same style. Suppose we have to apply the same styling to two or three different elements on our page, then we don't need to write different CSS codes for them, instead, we can use a group selector for this purpose.
Example -
Inside an Element :
With this, you can target elements inside the parent element. Let's understand by the example-
Example -
Direct child :
You can target an element that is directly inside a parent element. See the below example -
Example -
In the above example, Only one li background changed because that is the direct child of div tag. p and ul element are also direct child of div tag.
Sibling ~ or + :
If you want to style the element next to the selected element, then where we can use this selector for style.
Example -
In the above example, I have given a class to the third and seventh p elements and targeted the fourth p element and all the elements after the seventh element by the help of (+) and (~) respectively.
Pseudo Selector -
::before selector -
With the help of ::before pseudo selector, you can insert some content before the content of an element.
Example -
::after selector -
With the help of ::after pseudo selector, you can insert some content after the content of an element.
Example -
:hover Pseudo-class -
With the help of the hover pseudo-class, you can add special effects to an element when the mouse pointer is over it.
Example -
That's all in this article, Thanks for reading -