CSS :first-of-type 伪类选择一个元素,该元素是其父元素的子元素列表中该类型的第一个元素。
它与 :nth-of-type 相同。
:first-of-type 选择器实际上类似于 :nth-child,但有一个区别:它不太具体。
:first-of-type 选择器仅针对与类似兄弟姐妹相关的排列中元素的特定类型。
从 Selectors Level 4 开始,被选元素不需要有父元素。
语法
:first-of-type { css declarations; }
:first-of-type 选择器的例子:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p:first-of-type { background: #8ebf42; } </style> </head> <body> <h2>:first-of-type selector example</h2> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </body> </html>
带有 <article> 标签的 :first-of-type 选择器示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p:first-of-type { font-size: 22px; color: #777777; } </style> </head> <body> <h2>:first-of-type selector example</h2> <article> <h2>This is a title.</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. .</p> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. .</p> </article> </body> </html>
带有一些 HTML 标签的 :first-of-type 选择器示例:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <style> p { margin: 0; } article:first-of-type { background-color: #777777; color: #ffffff; } </style> </head> <body> <h2>:first-of-type selector example</h2> <article> <p>This is a first element!</p> <p>This <em>nested 'em' is first</em>!</p> <p>This nested 'strong' is first, but this nested 'strong' is last!</p> <p>This <span>nested 'span' gets styled</span>!</p> <q>This is a 'q' element!</q> <p>This is a last element.</p> </article> </body> </html>
日期:2020-06-02 22:14:29 来源:oir作者:oir