博客列表 >CSS 权重与结构伪类

CSS 权重与结构伪类

PHui
PHui原创
2022年10月21日 15:01:28312浏览

1. 实例演示权重的原理与计算方式

CSS

  1. /* ! 选择器权重 */
  2. /* ? 1. 实体标记: id, class, tag */
  3. /* ? 2. 排列顺序: id, class, tag */
  4. /* ? 3. 记数方式: 选择器中的实体标记数量 */
  5. /* ! 1. 权重表示方法 */
  6. /* ? ( 0, 0, 1 ): id=>0, class=>0,tag=>1 */
  7. /* ? id = null = 0 */
  8. /* ? class = null = 0 */
  9. /* ? tag = h1 = 1*/
  10. h1 {
  11. color: aliceblue;
  12. }
  13. /* ? (0,1,1) = id=>0,class=>1, tag=>1 */
  14. /* ? id = null = 0 */
  15. /* ? class = title = 1 */
  16. /* ? tag = h1 = 1*/
  17. h1.title {
  18. color: red;
  19. }
  20. /* ? ( 1, 1, 1) = id=>1,class=>1,tag=>1*/
  21. /* ? id = active = 1 */
  22. /* ? class = title = 1 */
  23. /* ? tag = h1 = 1 */
  24. h1#active.title {
  25. color: red;
  26. }
  27. /* ! 2. 权重优先级 */
  28. /* ? (0,0,1) , (0,0,2) : (0,0,2)权重大 */
  29. h1 {
  30. color: red;
  31. }
  32. body h1 {
  33. color: blue;
  34. }
  35. /* ! 3. 权重注意事项: 尽量不要在 `html` 中使用 `id`属性 */
  36. /* ? 1. id 权重过大, 位于权重顶端 */
  37. /* ? 2. id 会导致选择器失去弹性/弹性不足, 不利于调试或复用 */

2. 实例演示结构伪类,通过位置关系匹配子元素

HTML

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <link rel="stylesheet" href="css/fake.css" />
  9. </head>
  10. <body>
  11. <ul class="list">
  12. <li class="item">item1</li>
  13. <li class="item">item2</li>
  14. <li class="item">item3</li>
  15. <li class="item">
  16. item4
  17. <ul>
  18. <li class="item">item4-1</li>
  19. <li class="item">item4-2</li>
  20. <li class="item">item4-3</li>
  21. </ul>
  22. </li>
  23. <li class="item">item5</li>
  24. <li class="item">item6</li>
  25. <li class="item">item7</li>
  26. <li class="item">item8</li>
  27. </ul>
  28. </body>
  29. </html>

CSS

  1. /*
  2. ! :nth-of-type(an + b)
  3. * 1. a: 系数
  4. * 2. n: 参数
  5. * 3. b: 偏移量
  6. */
  7. /* ? a = 0 : 匹配一个 */
  8. /* ? 匹配第3个 */
  9. .list > li:nth-of-type(3) {
  10. background-color: lightgreen;
  11. }
  12. /* ? a =1 : 匹配一组(正向) */
  13. /* ? 从第六个开始匹配到最后一个 */
  14. .list > li:nth-of-type(n + 6) {
  15. background-color: lightblue;
  16. }
  17. /* ? a =-1 : 匹配一组(反向) */
  18. /* ? 从第二个开始匹配到第一个 */
  19. .list > li:nth-of-type(-n + 2) {
  20. background-color: lightyellow;
  21. }
  22. /* ? 快速获取第一个和最后一个: 语法糖 */
  23. /* 第1个 */
  24. .list > li:first-of-type {
  25. background-color: lightgreen;
  26. }
  27. /* 最后1个 */
  28. .list > li:last-of-type {
  29. background-color: lightgreen;
  30. }

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议