Scott

css: 伪类选择器 a year ago

css
2816个字符
共有104人围观

常见css伪类选择器

CSS 中的伪类(pseudo-classes)是一种特殊的选择器,它允许你在不修改 HTML 结构的情况下,对元素进行样式控制。常见的伪类选择器如下:

  • :link:用于选取所有未被访问过的链接。例如,a:link { color: blue; } 会将所有未点击过的链接设置为蓝色。
  • :visited:用于选取所有已经被访问过的链接。例如,a:visited { color: purple; } 会将所有已访问过的链接设置为紫色。
  • :hover:用于选取鼠标悬停在元素上时的状态。例如,a:hover { background-color: yellow; } 会使鼠标悬停在链接上时将背景颜色设置为黄色。
  • :active:用于选取被点击或激活的元素。例如,a:active { color: red; } 会将被点击的链接设置为红色。
  • :focus:用于选取获得焦点的元素(通常是输入框)。例如,input:focus { border-color: blue; } 会将获得焦点的输入框边框颜色设置为蓝色。
  • ::selection:用于选取被用户选中的文本部分。例如,::selection { background-color: lightblue; color: black; } 会在选定文字时将背景色设置为浅蓝色,文字颜色设置为黑色。
  • :first-child:用于选取父元素的第一个子元素。例如,div > p:first-child { font-size: 20px; } 会将 div 下面的第一个 <p> 元素字体大小设置为 20px。
  • :last-child:用于选取父元素的最后一个子元素。例如,div > p:last-child { font-size: 16px; } 会将 div 下面的最后一个 <p> 元素字体大小设置为 16px。
  • :nth-child(an+b):用于选取父元素中第 n * an + b 个子元素。例如,li:nth-child(2n) { background-color: yellow; } 会将列表项的偶数位置设为黄色。这里的an+b可以填odd(奇数), even(偶数), 从1开始,并不是指索引.
  • :not():用于选取不符合某一条件的元素。例如,a:not(:hover):link { color: blue; } 会在鼠标悬停时将链接颜色更改为红色,否则保持蓝色。
  • :target:用于选取当前活动区域(锚点)所指向的元素。例如,#nav a[href="#about"]:target { background-color: lightblue; } 会将 #about 锚点指向的 nav <a>元素背景色设置为浅蓝色。
  • :lang():用于选取具有特定语言属性值的元素。例如,p:lang(zh) { font-family: "宋体"; } 会将 zh 语言属性值对应的元素字体设置为“宋体”。
  • :matches():用于选取匹配多个简选子句的元素,例如 a:matches(:hover, :focus) { color: red; } 会将鼠标悬停或获得焦点时链接设置为红色。
  • :is(): 与 :matches() 类似,用于选取匹配多个简选子句的元素,但是它更灵活一些,可以根据条件进行逻辑运算。例如:a:is(:hover, :focus) { color: red; }
  • ::placeholder{}:用于设置 placeholder 属性值对应的元素样式。例如,input::placeholder{color: gray;} 会将 input 元素的 placeholder 文本颜色设为灰色。
  • ::before::after 伪元素,可以在生成了HTML代码之前或之后插入额外的内容。

example

/* 1. :link */
a { color: blue; }

/* 2. :visited */
a:visited { color: purple; }

/* 3. :hover */
a:hover { background-color: yellow; }

/* 4. :active */
a:active { color: red; }

/* 5. :focus */
input:focus { border-color: blue; }

/* 6. ::selection */
::selection { background-color: lightblue; color: black; }

/* 7. :first-child */
div > p:first-child { font-size: 20px; }

/* 8. :last-child */
div > p:last-child { font-size: 16px; }

/* 9. :nth-child(an+b) */
li:nth-child(2n) { background-color: yellow; }

/* 10. :not() */
a:not(:hover):link { color: blue; }

/* 11. :target */
nav a[href="#about"]:target { background-color: lightblue; }

/* 12. :lang() */
p:lang(zh) { font-family: "宋体"; }

/* 13. :matches() */
a:matches(:hover, :focus) { color: red; }

/* 14. :is(): 与 :matches() 类似,用于选取匹配多个简选子句的元素,但是它更灵活一些,可以根据条件进行逻辑运算。例如:a:is(:hover, :focus) { color: red; } */
/* a:is(:hover, :focus) { color: red; } */

/* 15. ::placeholder{} */
input::placeholder{color: gray;}

了解更多,请参看: https://www.w3schools.com/cssref/pr_list-style-type.php