All About CSS Selectors
In this blog, we will cover various types of selectors used in CSS to target elements with examples.
The most important part of the CSS is targeting specific elements and styling those. In this blog, we will go through some of the frequently used selectors with examples.
Universal Selectors
These selectors will select all the elements in the HTML page. A common use case is to remove padding and margin for all the elements.
Type Selector/Element Selector
Type selectors are used for targeting specified elements in the HTML like all the div, span, or li elements.
In the above codepen, we have targetted the div, span, and li elements by using Type selector.
Class Selector
We can select the classes assigned in the HTML by adding . before the class name in the CSS.
- it is the most commonly used selector because we can create a class and assign the class to multiple elements to apply style.
Id Selector
It is similar to the class selector, the only difference is we can target Id's by using this selector.
- We can target elements by adding # before the Id.
Chained Selector
We can chain(similar to And condition) multiple selectors and target elements by using this selector.
- In the above example, it will apply styles to every orange class in the li tag.
Combined Selector
This selector is used to combine multiple selectors and apply styles to elements.
- Here we are applying same styling to span and orange class by using combined selector
Selecting Inside elements
We can select elements inside the specified elements directly by using this.
- We can select all the li elements inside the ul. In the same way, we can select all span elements inside a div element.
- In the above codepen we have selected all the span elements inside the div and all li elements inside the ul element.
Direct child selector
it selects direct child elements inside specified elements.
Sibling Selector
We can select the sibling elements to the specified element by using this selector.
- ~ selector is used to select every single sibling after the specified element.
- + selector is used to select only the direct sibling very next to the specified element.
Thanks for reading this blog.