As I mentioned in a previous post, CSS has five categories of selectors. The basic category includes the Universal Selector (*), Tag selectors, Id selectors, and Class selectors. Now, let's get to know each of them.
1. Universal Selector
It is denoted by an asterisk(*). This selector selects all the elements on a webpage. For example:
A most common example that you have seen of the Universal Selector is,
This snippet removes browser default margin and padding of all the elements on a webpage.
2. Tag selector
It selects all HTML elements with the specified tag name.
For example: to select all divs on a webpage using the tag name, we simply write,
3. ID selector
It selects an HTML element with a unique name. A unique name is given to an HTML element in the "id" attribute of the element. The element can then be styled by using the id preceded with a hash(#) symbol.
Note: Id is a unique name so, no two elements can have the same id.
4. Class selector
A class selector selects a group of HTML elements having the same name. A class name can be given to multiple HTML elements in the "class" attribute of every element that you want to be part of the group. The elements can then be styled by using the class name preceded with a dot(.) symbol.
For Example:
Combining the Basic Selectors
All the basic selectors can also be used in combination with each other as per requirements. These combinations are other than the Combinator Selectors and no other symbol is required to combine them.
Example 1: To select all divs with class name "teal", we can use
Example 2: We can also use a combination in which multiple tag names or class names or ids are separated by a comma, to apply styling to all those elements i.e.
Here's the example for this,
These are just a few examples and these selectors can be combined in a lot of ways.
Although basic selectors are easy to use, there can be issues of the precedence so, they must be used with care. The topic is itself a bit detailed so I may be writing something on it in the future. For now, at least basic selectors are making sense hopefully.π
Next time, I will be explaining Combinators.
Till then, you may leave your queries and suggestions in the comments below.π
Top comments (11)
The universal selector does not match βall the elements on the page,β it matches all elements within a scope. When the
*
is unscoped it matches the whole page, but it can be used in conjunction with other selectors. For example, say.content p *
to target any elements nested inside paragraph content.Thanks for clarifying. ππ» I hadn't any idea if CSS too has scopes.
Thanks for sharing... really helpful for nobs
Glad to know you found this useful π
Donβt for get about box-sizing: border-box; in the universal selector.
I am learning React, this is good to help me the understand CSS better
Glad to know you found this useful π
Some comments may only be visible to logged-in visitors. Sign in to view all comments.