Knowing when to use a particular selector can be a chore. In this short post, I'll show you how to know when exactly to use different types of selectors when styling with CSS.
1. Type selector
Use this when you need to style all or most of the instances of an HTML element the same way
Here's a quick example:
2. ID selector
If you want to style a unique element, this is your best bet. You should use an ID selector for only unique styles you don't want to repeat again. This is because IDs are unique elements in HTML and can only be used once in a page.
Here's an example:
3. Class selector
If you have elements that are reusable and specific, class selectors are great for those.
In the example above, .beauty-products can be used for multiple HTML elements in your code and they will all be aligned to the left and have a color of pink.
4. Descendant selector
In CSS, a descendant selector is one that selects the elements that are descendants of a specified element. For instance, if you have a div element that houses a h3 element and a p tag, the hierarchy will look something like this:
div element - superior/parent element
h3 element - descendant element
p tag - descendant element
To style these descendant elements, you should use a descendant selector.
Here's an example:
Ideally, you should not go deeper than three levels like this:
While it actually works, it is not recommended as many selectors can cause your page to load slowly.
So, that's how you choose selectors in CSS. Hope you've found this post helpful!
Top comments (1)
This was such an interesting read!
Yesterday I had to make a pure CSS animation and these two selectors came through for me:
Made me realise how powerful CSS truly is and that sometimes, we don't even need JavaScript.