CSS Selectors: Most Easy Ways to Understand
In this article, I am going to show you the easiest ways to understand and use CSS selectors. This is your first step in CSS. Selectors are a very important part of Cascading Style Sheets. We use selectors to select the HTML elements which we want to style. Selectors are the basic thing that we use to select HTML elements and then apply styles to the HTML elements.
So, without losing time let’s start.
Five Categories of CSS Selectors
- Simple selectors (in order to select Elements names, class and id)
- Combinator selectors (to select elements with a specific relation between them)
- Pseudo-Class selectors (to select a class for specific styling)
- Pseudo-Element selectors (for selecting an element for specific styling)
- Attribute selectors (we can also select elements with their attributes)
List of All CSS Selectors Which We Will Learn
Click the links below to jump on the topic:
CSS element selector
Elements selector is used to select the HTML elements based on their names. We simply type the name of the HTML element and then type a pair of curly braces and define the properties of CSS in between them. The below image shows the example of the CSS element selector.
CSS .Class Selector
Class is an attribute of HTML. The class selectors are used to select the element with a specific class name. In order to select the class of an element, we use the period (.) character followed by the class name. So, see the example below.
Note: Class name should not start with a number. Although we can add numbers at the end.
CSS #Id Selector
It is also an attribute of HTML. We use the hash (#) character followed by the id name. As you can see in the examples below.
Note: Id name should not start with a number.
Universal Selector is used to select all the elements in the HTML. So, we use this with an asterisk (*) sign. As you can see in the example below.
Group selectors select all the HTML elements and apply the same style to them. Such as h1, h2, p, div etc.
The combinator selectors explain the relationship between the selectors.
Five Types of Combinator Selectors
- descendant selector (separate by space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)