17

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Hai Tien
  • 2,929
  • 7
  • 36
  • 55

2 Answers2

26

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

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
12

As Pranav c said, you can use .page a:first-of-type { ... } or .page a:nth-of-type(1) { ... } but neither of them will work in IE8

So if we can assume that the <span> is always going to be there, then

.page span+a { ... }

will ensure that only the first a after the span will be styled and this is as good as you can get cross-browser right now.

Example: FIDDLE

Ivan Nikolchov
  • 1,574
  • 1
  • 27
  • 41