02 结构伪类选择器
结构伪类选择器中的伪元素和伪选择器是CSS已经定义好的,直接使用即可,不可以随意修改
a.伪元素 first-child:父元素的第一个子元素last-child:父元素的最后一个子元素nth-child(n):父元素的第n个子元素first-of-type:父元素内具有指定类型的第一个元素last-of-type:父元素内具有指定类型的最后一个元素nth-of-type(n):父元素内具有指定类型的第n个元素 b.结构伪类选择器的格式 选择器:伪元素{声明;}功能: 以E F :first-child{background:red;}为例,它的功能是将E下的第一个与F匹配的子元素变为红色背景以E :first-child{background:red;}为例,它的功能是先找到E的父元素,在父元素下的子元素中找到第二个类型为E的元素变为蓝色背景以E :nth-of-type(2) {background:blue;}为例,它的功能是先找到E的父元素,在父元素中找到第二个类型为E的元素变为蓝色背景 程序示例: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> p,li{ border: 1px solid red; } /*需求:选择body下面的第二个元素 E:nth-child(n) --> 找到E元素的父级元素 , 寻找父级元素的第n个与E相匹配的子元素 , 如果该元素不匹配,就不会被选择.*/ p:first-child{ background: yellow; } li:nth-child(2){ background: blue; } /* E : nth-of-type(n) --> 找到E的父级元素 , 然后在他的父级元素中去找第n个与E元素相匹配的同级元素 */ p:nth-of-type(3){ background: brown; } </style></head><body><h1>Table</h1><p>1</p><p>2</p><p>3</p><ul> <li>li1</li> <li>li2</li> <li>li3</li></ul></body></html> 运行结果03 属性选择器 a.属性选择器 E[attr] 选择匹配具有属性attr的E元素E[attr=val] 选择匹配具有属性attr的E元素,并且属性值为val(其中val区分大小
写)E[attr^=val] 选择匹配元素E,且E元素定义了属性attr,并且其属性值是以val开头的任意字符串E[attr$=val] 选择匹配元素E,且E元素定义了属性attr,并且其属性值是以val结尾的任意字符串E[attr*=val] 选择匹配元素E,且E元素定义了属性attr,并且其属性值包含了val,换句话说,字符串val与属性值中的任意位置相匹配 b.格式 选择器[id/class=“val”]{声明;}理解:先定义属性,再选择属性 程序示例 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> /* 属性选择器 */ a[id]{ background: blue; } a[class]{ background: black; } a[href^="https"]{ background: red; } a[id=a]{ background: yellow; } a[class="W"]{ background: green; } a[href*="."]{ background: pink; } </style></head><body><p class="demo"> <a rel="external nofollow" href="https://www.baidu.com" class="links" id="a">1</a> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="" class="Q">2</a> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="" class="links" id="a">3</a> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="" class="W">4</a> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="" id="b">5</a></p></body></html> 运行结果