CSS选择器 first-child 、first-of-type 和 nth-of-type()

块内区域首个元素的css样式可以通过first-child、first-of-type 和 nth-of-type()实现。对于 IE8 及更早版本的浏览器中,必须声明

  • first-child:选择器用于选取属于其父元素的首个子元素的指定选择器
  • first-of-type:选择器匹配属于其父元素的特定类型的首个子元素的每个元素
  • nth-of-type(x):选择器匹配属于其父元素的特定类型的第x个子元素的每个元素

code1:first-child
body和第一个div中的首个p有效,第二个p和第三个span无效,因为p是首个子元素
第二个div中的span有效,p无效,因为span是首个子元素。
结论:该选择器是以块内区域划分的,块内区域的所有子块区域的的子元素也会生效,但是必须是首个子元素才有效。


<html>
<head>
<style>
p:first-child
{
background-color:yellow;
}
span:first-child
{
background-color:yellow;
}
style>
head>
<body>
<p>这个段落是其父元素(body)的首个子元素。p>
<p>这个段落是其父元素(body)的第二个个子元素。p>
<span>这个span是其父元素的第三个个子元素。span>
<div>
<p>这个段落是其父元素(div)的首个子元素。p>
<p>这个段落是其父元素(div)的第二个个子元素。p>
div>
<div>
<span>这个段落是其父元素(div)的首个子元素。span>
<p>这个段落是其父元素(div)的第二个子元素。p>
div>
body>
html>

CSS选择器 first-child 、first-of-type 和 nth-of-type()_第1张图片

code2:first-of-type
body和两个div中的第一个p和第一个span均生效,因为p或span为所有为p或span的子元素中的第一个
结论:该选择器也是以块区域划分的,所有子块均有效,只需要是同类标签中首个元素即可。

p:first-of-type
{
background-color:yellow;
}
span:first-of-type
{
background-color:yellow;
}

CSS选择器 first-child 、first-of-type 和 nth-of-type()_第2张图片
code3:nth-of-type(1)和first-of-type效果相同,一般常用于table单双行样式中

p:nth-of-type(1)
{
background-color:yellow;
}
span:nth-of-type(1)
{
background-color:yellow;
}

你可能感兴趣的:(CSS)