:first-child selector
Using the :first-child selector, you can target or select the very first element inside an element, like a DIV. You can use any other element as a container like <section> or <article> etc.
Here’s an example.
I have three child elements inside the parent <div> element. I want to target the 1st element, a <p> element and add some special style to it.
<head>
<style>
#container>:first-child {
text-align: right;
border: dotted 2px red;
}
</style>
</head>
<body>
<div id='container'>
<p> element 1 </p>
<div> element 2 </div>
<div> element 3 </div>
</div>
</body>
The pseudo-class selector :first-child is used to style elements that fall into the parent-child relationship.
Note: A pseudo-class has a colon :. For example a:hover { font-size: 10px; }
Here’s another way you can use the above example. Instead of id reference, I am not using the element reference.
div>:first-child {
text-align: right;
border: dotted 2px red;
}
The result will be same.
Using :nth-child() selector
This pseudo-class selector is used to match elements based on their position in a group of child elements. Again, there should be a parent child relationship among elements to work with this selector.
div>:nth-child(1) {
text-align: right;
border: dotted 2px red;
}
I have provided it with the number "1", since I am targeting the first child element.
You can use id reference too.
#container>:nth-child(1) {
text-align: right;
border: dotted 2px red;
}