Minh Anh Minh Anh - 5 months ago 8
CSS Question

How to style for first-child?

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.

Answer

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