For example, I have HTML like :
<div class='page'>
<span>2</span>
<span>2</span>
<a>1</a>
<a>6</a>
</div>
How can I style for first child a
I used like this : .page a:first-child {color:red}
but it doesn't run.
You will begin by using the type selector to select HTML elements to style. Then, you will combine selectors to identify and apply styles more precisely. Lastly, you will group several selectors to apply the same styles to different elements.
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
Definition and Usage. The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
Use first-of-type
instead of first-child
.page a:first-of-type{
color:red;
}
The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.
Taken from MDN Documentation. You can find more details & examples here.
Explanation : :first-child not working as expected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With