The :first-child pseudo-class allows you to target the first element immediately inside another element or match a specified element that is the first child of another element. In the following example, the selector matches any <p> element that is the first child of any element:
HTML file: | Displayed by browser: |
---|---|
<style>
p:first-child { color: blue; } </style> <body> <p>This is a first-child text of the body element.</p> <p>This is a second-child text of the body element.</p> <p>This is a third-child text of the body element.</p> </body> |
This is a first-child text of the body element. This is a second-child text of the body element. This is a third-child text of the body element. |
Note: For :first-child to work in IE8 and earlier, a DOCTYPE must be declared.