Table of contents
No headings in the article.
As the name suggests CSS Selectors help in selecting the HTML elements that needs to be styled. To dive deeper Click Here
- Simple selectors
- Combinator selectors
- Psuedo-class selectors
- Pseudo-element selectors
- Attribute selectors
1) Simple selectors There are basic level selectors used to select HTML elements based on name, id, class.
p{
color: red; /* selects all p tags and change the color to Red */
}
#para-id{
color: blue; /* selects any the tag the contains id="para-id" and changes the color to bl
ue*/
}
.para-third{
color: green; /* selects any tags that contains class="para-third" and applies green color*/
}
p.para-class{
color: black; /* selects only the para tag that contains class="para-class" and applies black color*/
}
Universal selector This selects all the elements inside HTML body tag and applies the provide CSS.
*{
color : lightblue; /* every elements including/inside body tag with have text color of lightblue */
}
Grouping selector It is a method of combining two or more name, id, class and apply styles to them.
h1, p, a{
color : red; /* This applies red color to all three h1, p, a*/
}
2) Combinator selector Combinator selectors helps in selecting the elements based on parent child relationship.
- Descendant selector (space)
- Child selector (>)
- Adjacent sibling selector (+)
- General sibling selector (~)
Descendant selector
div p{
border : 1px solid black; /* select all the p elemets inside the div element*/
}
Child selector
div > p {
color : green; /* selects all p elements which is the direct child of div element */
}
Adjacent sibling selector
div + p {
color : blue; /* selects the p element which is sibling and comes right next to div element*/
}
General sibling selector
div ~ p {
color : purple; /* selects all p elements that are next siblings of a div element */
}
3) Psuedo-class selectors (:) Used to apply/change style to elements when the state of the element in modified/changed.
button{
background-color : blue ;
}
button:hover{
background-color : transparent; /* When mouse is hovered over the button backgound becomes transparent */
}
There are more Pseudo-class selectors, For more selectors Check Here
4) Psuedo-element selectors (::) Used to apply/change style specific part of elements.
p{
font-size : 10px;
}
p::first-letter{
font-size : 20px; /* Make first letter of p element bigger */
}
There are more Pseudo-element selectors, For more selectors Check Here
5) Attribute selector ([]) Helps selecting elements using attributes.
input[type="text"]{
padding : 10px; /* Appies padding to input elements of type text*/
}
One can also create their own custom attributes to an element and use them as selector. Check Here
Happy Learning :)