css :first-of-type选择器实例讲解

时间:2016-08-04
css :first-of-type选择器用于匹配父元素的第一个特定子元素,比如p:first-of-type用于匹配父元素里的第一个p元素,本文章向大家介绍css :first-of-type选择器的基本使用方法,需要的朋友可以参考一下。

css :first-of-type介绍

css :first-of-type选择器用于匹配父元素的第一个特定子元素。

语法:

:first-of-type { 
   style properties 
}

如:p:first-of-type用于匹配父元素里的第一个p元素。

css :first-of-type实例

设置其父级的第一个p元素的背景色

<!DOCTYPE html>
<html>
<head>
<style> 
p:first-of-type
{
background:#ff0000;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
/* http://www.manongjc.com/article/1306.html */
</body>
</html>

在线运行

再看一个实例:

<!DOCTYPE html>
<html>
<head>
<style>
p:first-of-type
{
background-color:yellow;
}
</style>
</head>
<body>
<p>码农教程</p>

<h1>java教程</h1>
<p>php教程</p>

<div>
  <span>css教程</span>
  <p>mysql教程</p>
  <p>html教程</p>
</div>
<div>
  <p>sql教程</p>
  <p>js教程</p>
</div>
</body>
</html>

运行结果如下:

css :first-of-type选择器实例讲解

p:first-of-type需要注意两点:

  1. 第一,是在整个HTML文档中匹配
  2. 第二,p:first-of-type选取的是父元素里的第一个子元素p标签,并不要求父元素的第一个子元素必须是p标签。

上面实例中,body的第一个p标签子元素为"<p>码农教程</p>",所以该元素会被选中。

同理“<p>mysql教程</p>”和"<p>sql教程</p>"作为div(class为div1和class为div2)元素的第一个p标签,所以也会被选中.