Hai Tien
Hai Tien

Reputation: 3117

How to style for first-child of a certain type of element?

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.

Upvotes: 17

Views: 1723

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115272

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

Upvotes: 26

Ivan Nikolchov
Ivan Nikolchov

Reputation: 1584

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

Upvotes: 12

Related Questions