Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 544
Hai Tien Avatar asked Dec 27 '13 14:12

Hai Tien


People also ask

How do you apply style to several specific element types?

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.

How do you select the first child of an element in CSS?

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.

How do I select a specific Nth child in CSS?

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.


1 Answers

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

like image 193
19 revs, 3 users 90% Avatar answered Oct 10 '22 11:10

19 revs, 3 users 90%