What are CSS Selectors?
CSS selectors basically direct the browser to which CSS properties should be used for a particular HTML tag.
Types of CSS Selector
- Universal Selector
Universal selectors denote with '*' and target an entire HTML page.
*{ background-color: rgb(128, 128, 128); background-image: linear-gradient(pink, yellow, blue) ; }
- Individual Selector
Individual selectors select the entire selected elements within the HTML for injecting the property of CSS.
p { background-color: blue; }
- Class and id Selector
Class selector denotes by '.' and selects the exact class which is targeted. it could be applied to many elements. whereas the Id selector denotes by '#' and also selects the exact id which is targeted but it should be unique.
class - .tableClass { background-color: rgb(82, 60, 147); }
id - #table { border: 3px; color: brown; text-align: center; }
- And(chained) Selector
And selector basically selects from multiple ids or class or from both and all the conditions has to be true.
ul.demo-class.tableClass { background-color: beige; font-size: 30px; }
- Combined Selector
This selector comes to a place when we need to apply the same properties to different elements.
p, li, span { background-color: brown; font-size: 19px; }
- Inside an element
In this we can select the Element inside an element and write with the help of 'space'.
div ul li { background-color: pink; }
- Direct child
It selects the direct child of an element, there could be many direct child elements, and whichever child is selected will get the CSS properties injected.
div > li > p { background-color: orange; }
- Sibling
This selector is denoted by '~' or '+'. It needs a class or an id, If some element has a class and is selected to inject CSS, then this allows to select the just immediate of that class by adding a '~' or '+' sign.
.foodtree + p { background-color: blue; font-family: Verdana, Geneva, Tahoma, sans-serif; }
Pseudo-Selectors ( ::before and ::after)
:: before and :: after - It works with double colon '::' and must-have content and display property. By default it is inline. In:: before, it creates an artificial element at first of the selected element. whereas in::after, it creates an artificial element at the last of the selected element.
.foodtree::before { content: '', display: block; width: 15px; height: 15px; margin-right: 5px; }
.foodtree::After{ content: '', display: block; width: 15px; height: 15px; margin-right: 5px;