语法
:first-child { css declarations; }
带有 <p> 标签的 :first-child 伪类示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p:first-child { background-color: #1c87c9; color: #fff; } </style> </head> <body> <p>Lorem ipsum is simply dummy text...</p> <h2>First-child selector example</h2> <p>Lorem Ipsum is simply dummy text...</p> </body> </html>
带有 <li> 标签的 :first-child 伪类示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> li:first-child { background: #8ebf42; } </style> </head> <body> <h2>:first-child selector example</h2> <ul> <li>Paris</li> <li>Moscow</li> <li>Rome</li> </ul> <ol> <li>Paris</li> <li>Moscow</li> <li>Rome</li> </ol> </body> </html>
带有 <ol> 标签的 first:child 伪类示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> ol:first-child { background: #8ebf42; } </style> </head> <body> <ol> <li>London</li> <li>Paris</li> <li>Rome</li> </ol> <ol> <li>London</li> <li>Paris</li> <li>Rome</li> </ol> </body> </html>
带有 <em> 标签的 :first-child 伪类示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p em:first-child { background: #82b534; } </style> </head> <body> <h2>:first-child selector example</h2> <article> <p>Here is a <em>some</em> text. This is a <em>example</em>.</p> <p>Here is a <em>some</em> text. This is a <em>example</em>.</p> <p>Here is a <em>some</em> text. This is a <em>example</em>.</p> </article> </body> </html>
带有 <ul> 标签的 :first-child 伪类示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> ul li { color: blue; } ul li:first-child { color: #8ebf42; font-weight: bold; } </style> </head> <body> <h2>:first-child selector example</h2> <ul> <li>List Item 1</li> <li>List Item 2</li> <li> List Item 3 <ul> <li>List Item 3.1</li> <li>List Item 3.2</li> <li>List Item 3.3</li> </ul> </li> </ul> </body> </html>
CSS :first-child 伪类选择元素,如果它是其他元素中的第一个子元素。
如果用户想要选择和应用第一段的样式,可以使用 :first-of-type 选择器。
:first-child 选择器实际上类似于 :first-of-type 但有一个区别:它不太具体。
:first-child 只匹配父元素的第一个子元素,而 :first-of-type 匹配指定元素的第一个子元素,即使它不是第一个元素。
日期:2020-06-02 22:14:29 来源:oir作者:oir