博客列表 >CSS常用伪类

CSS常用伪类

浮沉
浮沉原创
2021年01月31日 16:44:47599浏览

CSS 伪类选择器

常用伪类选择器:
1.匹配任意位置的元素:”:nth-of-type(an+b)”
其中:an+b: an起点,b是偏移量, n = (0,1,2,3…);even 索引是偶数的子元素,odd索引是奇数的子元素;
2.反向获取任意位置的元素:”:nth-last-of-type(an+b)”;
3.选择第一个子元素:”:first-of-type”;
4.选择最后一个子元素:”:last-of-type”.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>伪类选择器</title>
  7. <style>
  8. /* 1.匹配任意位置的元素:":nth-of-type(an+b)"
  9. an+b: an起点,b是偏移量, n = (0,1,2,3...)
  10. even 索引是偶数的子元素,odd索引是奇数的子元素*/
  11. ul li:nth-of-type(1n + 2) {
  12. background-color: cyan;
  13. }
  14. ul li:nth-of-type(even) {
  15. background-color: darkred;
  16. }
  17. ul li:nth-of-type(odd) {
  18. background-color: darkturquoise;
  19. }
  20. /* 2.反向获取任意位置的元素:":nth-last-of-type(an+b)" */
  21. ul li:nth-last-of-type(-n + 3) {
  22. background-color: darkgoldenrod;
  23. }
  24. /* 3.选择第一个子元素:":first-of-type" */
  25. ul li:first-of-type {
  26. background-color: violet;
  27. }
  28. /* 4.选择最后一个子元素:":last-of-type" */
  29. ul li:last-of-type {
  30. background-color: wheat;
  31. }
  32. </style>
  33. </head>
  34. <body>
  35. <ul>
  36. <li>item1</li>
  37. <li>item2</li>
  38. <li>item3</li>
  39. <li>item4</li>
  40. <li>item5</li>
  41. <li>item6</li>
  42. <li>item7</li>
  43. <li>item8</li>
  44. <li>item9</li>
  45. <li>item10</li>
  46. </ul>
  47. </body>
  48. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议