结构化伪类选择器和伪元素选择器
常用的结构化伪类选择器
:root选择器:用于匹配文档根元素,在HTML中,根元素始终是html元素,所以使用该选择器定义的样式,对所有元素均生效。对于不需要的可单独设置样式进行覆盖。
<style> :root{color="red";} /*泛指所有元素*/ h2{color="blue";} /*特指h2*/ </style> 复制代码
:not选择器:适用于要对某个结构元素使用样式,但是想排出这个结构元素下面的子结构元素不使用这个样式的情况。
<style> body *:not(h3){ color:red; /*'*'号代表所有的,所以该设置仅排除h3*/ } </style> 复制代码
3.only-child 选择器:如果某个父元素仅有一个子元素,则使用这个。(独生子女)
<style> li:only-child{ color:red; } </style> <body> <ul> <li>选择器</li> </ul> 复制代码
first-child 和 last-child 选择器:用于父元素中的第一个或最后一个子元素的样式设计。
p:first-child{ color:blue; /*第一句话为粉色*/ } p:last-child{ color:pink; /*第二句为蓝色*/ } /*比如body中有四句话*/ <body> <p>第一句</p> <h3>第二句</h3> <p>第三句</p> <p>第四句</p> </body> 复制代码
5.nth-child(n) 和 nth-last-child(n) 选择器:是上个选择器的扩展,可以选择你想选择的子元素,像上个例子中无法完成的第2个或倒数第二个都可以,n就代表第几个。
6.nth-of-type(n) 和 nth-last-of-type(n) 选择器:用于匹配属于父元素的特定类型的第n个或倒数第n个子元素。
<style> p:nth-last-of-type(2){ color:red; /* 与上一个例子不同在于,这个只找p标签的元素,跳过其他标签*/ } </style> <body> <h1>什么?</h1> <p>什么?</p> <h2>什么?</h2> <p>什么?</p> </body> 复制代码
7.empty 选择器:用于选择没有子元素或文本内容为空的所有元素。
<style type="text/css"> p{ background-color:red; } :empty{ background-color:green; /*其他段落背景颜色都为红色,只有内容为空的那个背景颜色为绿色*/ } </style> <body> <p>选择器</p> <p>选择器</p> <p></p> <p>选择器</p> 复制代码
8.target 选择器:用于为页面中的某个target元素指定样式 (该元素的id被当作页面中的超链接来使用) 。只有用户单击了页面中的超链接,并且跳转到target元素后,:target
选择器设置的样式才会起效果。 使用:
<style type="text/css"> ...... dl{ display: none; } dl:target{ display:block; } </style> 复制代码
然后,比如你有一个id叫"ps",如:<div id = "ps">
,把它作为超链接就是<a href="#ps">
,这样你就可以实现跳转的效果了。
伪元素选择器
before 伪元素选择器
比如说在段落前加个小图标:
p:before{content:url(图片路径);}
。也可以自己设计,比如在段落前加一个10*10的小正方形。
p:before{ content: ""; width: 10px; height: 10px; display: inline-block;/*把行内元素转化为行内块*/ background-color: pink; 复制代码
效果: 2. after伪元素选择器:使用和before一样,就是位置前后的差别而已。
作者:un
链接:https://juejin.cn/post/7022065835204149284