:first-child
:first-child
is a pseudo-class which selects the target element if it is the first child of some other element. That is, :first-child
will match the element only if it is the first child of its parent.
For example, suppose you have the following HTML:
<article> <p> Lorem Ipsum... </p> <p> Another Lorem Ipsum... </p> </article>
The following will select and apply the styles to the first paragraph which, in this case, is the first child of its parent.
p:first-child { font-size: 1.5em; }
The above rule will not style the paragraph in the following example, because it is not the first child of its .container
parent.
<div class="container"> <h1>Heading</h1> <p> Lorem Ipsum... </p> </div>
Trivia & Notes
If you want to select and style the first paragraph inside a container, whether or not it is the first child, you can use the :first-of-type
selector, which, as the name suggests, will select the first element of its type, whether or not it is the first child of its parent. For example, p:first-of-type
will select the paragraph that comes after the heading in the above source code example, but will not match any other paragraph that comes after that.
The :first-child
pseudo-class, just like other pseudo-classes, can be chained with other selectors such as :hover
, for example, to provide hover styles for selected element. It can also be chained with pseudo-elements ::before
and ::after
. See the examples and live demo sections below for examples.
Examples
Suppose you have the following markup:
<article> <h1>Understanding :first-child</h1> <p> This is the first paragraph, but it"s not the first child of its parent. </p> <p> This is another paragraph. <span>This is a span inside the paragraph.</span> </p> <ul> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> </article>
The following rule will match the span
inside the second paragraph, because it is the first child of its parent.
span:first-child { color: grey; }
The following rule will match the first list item in the above unordered list.
li:first-child { text-decoration: underline; color: deepPink; }
The following rule will not match any of the above paragraphs, because none of them is a first child of its parent.
p:first-child { font-size: 1.5em; }
The following rule will wrap the span
in two parenthesis using the ::before
and ::after
pseudo-elements.
span:first-child::before { content: "("; color: deepPink; } span:first-child::after { content: ")"; color: deepPink; }
You can see the live demo in the next section.
Live Demo
View this demo on the Codrops PlaygroundBrowser Support
The :first-child
pseudo-class is supported in Chrome, Firefox, Safari, Opera 9.5+, Internet Explorer 7+, and on Android and iOS.
Notes
Internet Explorer 7 doesn’t update the styles when elements are added dynamically. In Internet Explorer 8, if an element is inserted dynamically by clicking on a link the first-child style isn’t applied until the link loses focus.