[CSS Selector] E:first-child
Using selector:first-child, you can apply styles to the first child element. This is commonly called a "pseudo-class." It is equivalent to specifying :nth-child(1). Does not work in IE7 or earlier.
To target all first child elements, use *:first-child or simply :first-child. Note that when written without >, such as :first-child, it applies to the first child element across all descendant elements. For example, div :first-child applies to the first child of every descendant within the div. Text nodes (anonymous blocks) are ignored.
Sample Code
div.hoge :first-child { color: red;} /* Makes the first child of all descendants inside a div with class "hoge" red. */
div.hoge1 > :first-child { color: blue;} /* Makes the first direct child of a div with class "hoge1" blue. */
Browser Preview
div.hoge :first-child { color: red;} /* Makes the first child of all descendants inside a div with class "hoge" red. */
div.hoge1 > :first-child { color: blue;} /* Makes the first direct child of a div with class "hoge1" blue. */
<div class="hoge">This is a text node. Text nodes are ignored. <p>This is the first p element inside the div with class "hoge".</p> <div> <p>This is the first p element inside the nested div inside "hoge".</p> <p>This is the last p element inside the nested div inside "hoge".</p> </div> <p>This is the last p element inside the div with class "hoge".</p> </div> <div class="hoge1"> <p>This is the first p element inside the div with class "hoge1".</p> <div> <p>This is the first p element inside the nested div inside "hoge1".</p> <p>This is the last p element inside the nested div inside "hoge1".</p> </div> <p>This is the last p element inside the div with class "hoge1".</p> </div>
Note: when combining element names, IDs, class names, or attributes with :first-child, the selector first checks if it is the first child, and then checks if it also matches the specified element name, ID, class, or attribute. For example, p.hoge:first-child only applies if the first child is a p element AND has the class "hoge". To filter by element type alone, use :first-of-type instead.
div div.hoge:first-child { color: red;} /* Applies if the first child of a div descendant is a div with class "hoge". */
<div> <div class="hoge">This is the first div with class "hoge" inside the outer div.</div> <div> <div>This is the first div inside the nested div.</div> <div>This is the last div inside the nested div.</div> </div> <div class="hoge">This is the last div with class "hoge" inside the outer div.</div> </div>
Browser Compatibility
3 or earlier ×
2 or earlier ×
2 or earlier ×
8 ○
7 ○
6 ×
8 or earlier ×
3 or earlier ×
Android Browser
4.4+ ○
3 or earlier ×※ Version data based on MDN.
If you find any errors or copyright issues, please contact us.