结构伪类选择器
结构伪类选择器(Structural Pseudo-class Selectors)是 CSS 中一种用于选择文档结构中特定位置或关系的元素的选择器。结构伪类选择器允许根据元素在文档中的位置、父元素、子元素等特定关系来进行选择。
笔记内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>结构伪类选择器</title>
<style>
/* 结构伪例选择器,是 html5 中功能 */
/* 所有 ul(无序列表)里的第一个子元素会被修饰 */
ul li:first-child{
background: red;
}
/* ul(无序列表)里的最后一个子元素会被修饰 */
ul li:last-child{
background: red;
}
/* ul(无序列表)里的第 3 个子元素会被修饰 */
ul li:nth-child(3){
background: red;
}
/* n 表示 ul 中所有 li 被修饰,2n 表示 ul 中偶数行的 li 被修饰 */
/* n = 0 1 2 3 4 5 6... 2n = 0 2 4 6 8... 4n = 0 4 8 12 16... */
ul li:nth-child(2n){
background: red;
}
/* n 表示 ul 中所有 li 被修饰,2n 表示 ul 中偶数行的 li 被修饰,2n+1 表示 ul 中奇数行的 li 被修饰 */
/* n = 0 1 2 3 4 5 6... 2n = 0 2 4 6 8... 2n+1 = 1 3 5 7 9...*/
ul li:nth-child(2n+1){
background: red;
}
/* ul(无序列表)里的偶数行元素会被修饰 */
ul li:nth-child(even){
background: red;
}
/* ul(无序列表)里的奇数行元素会被修饰 */
ul li:nth-child(odd){
background: red;
}
/* body 里面的第 2 个元素,且必须是 p 元素,就会被修饰,不是 p 元素,不会被修饰 */
p:nth-child(2){
background: red;
}
/* body 里面第 2 个 p 元素(从第一个 p 元素开始数,不是从第一个元素开始数),就会被修饰 */
p:nth-of-type(2){
background: red;
}
/* 给 p 元素的第一行设置样式,first-line 只能用于块级元素 */
p::first-line{
color: red;
}
/* 给 p 元素的首字母设置样式,first-letter 只能用于块级元素 */
p::first-letter
{
color:#ff0000;
font-size:xx-large;
}
/* p 元素中 class 属性值为 article,给其首字母设置样式 */
p.article:first-letter
{
color:#ff0000;
}
/* p 段落中,被选中的文字背景变成红色,文字变成白色 */
p::selection{
background-color: red;
color: white;
}
/* 在 h1 内容的前面插入图片(仍在 h1 里面),默认是行内元素 */
h1::before
{
content:url(logo.png);
}
/* 在 h1 内容的前面添加文字(仍在 h1 里面),默认是行内元素 */
h1::before
{
content:"我是标题";
background-color: yellow;
}
/* 在 h1 标签后插入图片(仍在 h1 里面),默认是行内元素 */
h1::after
{
content:url(logo.png);
}
</style>
</head>
<body>
<ul>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
</body>
</html>