Harshit paliwal
Posted on June 1, 2022
if you are a beginner or just starting with CSS these are some important selectors you must know.
What are CSS selectors?
selectors are used to target HTML element on the web page so that we can style those elements.
I am asuming that you already know basic selectors like id and class.
// class
<div class="Box"></div>
.Box{
color:'black'
}
// id
<div id="Box"></div>
#box{
color:'green'
}
Let's see some more use full selectors
* ( Universal selector )
*{
margin:0;
padding:0;
}
this is called Universal selector it is used to select every single element of the page.
.box *{
margin:0;
padding:0;
}
we can use a universal selector like this also here we are selecting every single child element of .box class.
div p ( descendent selector )
The next selector is called the descendent selector what descendent selector for example if you want to select every paragraph element inside a div you can use a descendent selector
div p{
font-size:2rem;
}
but don't use like this
x y z p .box
😂
div + p
It will select only the element that is immediately preceded by the former element. it will select the first paragraph after each div element
div + p{
color:'red';
}
div > p
the only diffrance between div p
and div > p
is its only select one direct child of div element
div > p{
color:'red';
}
div ~ p
the sibling combinator is same as div + p
but the only difference is div ~ p
select every element and div + p
only select one direct element
div ~ p{
color:'red';
}
Pseudo classes
X:checked
input[type=radio]:checked {
border: 1px solid black;
}
This pseudo-class will only target a user interface element that has been checked.
p:after p:before
this :after and :before classes are great They simply generate content around the selected element. and we can insert content with css also 🔥
pseudo-element
p::first-line
it is pretty useful first-line pseudo-element it select an element and then applies styling to the only first line of the element.
p::first-line{
color:'red'
}
nth-child
div:nth-child(n)
div:nth-child(2){
border: 2px solid black;
}
one of my favourite selector. nth-child(n) can select any child of div or any parent element nth-child(n) take parameter as an integer like if you want to select 1st child element of div you can do div:nth-child(1)
.
:first-child / :last-child
IF you want to select the first or last child you can simply use div:first-child
this will select the first child and div:last-child
this will select last child
conclusion
CSS selectors are cool and use full features if you are not using them in your code I encourage you to give them a try.
resource
Posted on June 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 27, 2024