
Use of first child and last child Selectors in CSS

Hi, this tutorial will teach you about the first-child and last-child selectors in CSS. So that you can easily understand how these selectors work in CSS. Both of these selectors will only work if the element that you have selected is actually the first or last child of it’s direct parent.
I will give you an example so that you can try it yourself to understand.
Example:
<ul> <li>List 1</li> <li>List 2</li> <li>List 3</li> <li>List 4</li> <li>List 5</li> </ul>
In the above code we have created a ul li list and now we are going to write some basic css for our ul li.
ul{ width: 100px; margin: 0; padding: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } ul li{ background-color: #333; color: #fff; }
The CSS given below will set the lightgreen background color to our first and last li
as you can see that we have used :first-child
and :last-child
here.
ul li:first-child{ background-color: lightgreen; } ul li:last-child{ background-color: lightgreen; }
If you are facing any problem with it you can ask me. I will try to help you on it asap.
Thanks for visiting.