博主信息
博文 30
粉丝 0
评论 0
访问量 19322
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
选择器权重与常用伪类选择器
天宁
原创
560人浏览过

选择器权重

  • !important (最高权限,忽略任何权重)
  • id 用于匹配唯一元素,尽量少用或者不用
  • class 可自定义,用于匹配一组元素
  • tag 标签,数量太少

!important(最高权限) > id > class > tag(标签)

  1. <!DOCTYPE html>
  2. <html lang="en">
  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>选择器权重</title>
  8. </head>
  9. <style>
  10. /* 最高权限 */
  11. h1 {
  12. color: yellow !important;
  13. }
  14. /* id=1,class=0,tag=0 权限是1,0,0 */
  15. #title-id {
  16. color: green;
  17. }
  18. /* id=0,class=1,tag=0 权限是0,1,0 */
  19. .title {
  20. color: blue;
  21. }
  22. /* id=0,class=0,tag=1 权限是0,0,1 */
  23. h1 {
  24. color: red;
  25. }
  26. </style>
  27. <body>
  28. <h1 class="title" id="title-id">在干嘛</h1>
  29. </body>
  30. </html>

伪类选择器

单个匹配

  1. /* 第一个 */
  2. .list > li:first-of-type {
  3. background: red;
  4. }
  5. /* 最后一个 */
  6. .list > li:last-of-type {
  7. background: red;
  8. }
  9. /* 第四个 */
  10. .list > li:nth-of-type(4) {
  11. background: red;
  12. }
  13. /* 倒数第三个 */
  14. .list > li:nth-last-of-type(3) {
  15. background: red;
  16. }

组匹配

匹配第2个元素以及后面所有元素

  1. /*
  2. 0+2=2
  3. 1+2=3
  4. 2+2=4
  5. 3+2=5
  6. 4+2=6
  7. ...
  8. */
  9. .list > li:nth-of-type(n + 2) {
  10. background: chocolate;
  11. }

取前3个

  1. /* 取前3个
  2. -0+3=3
  3. -1+3=2
  4. -2+3=1
  5. -3+3=0 不可用
  6. */
  7. .list > li:nth-of-type(-n + 3) {
  8. background: chocolate;
  9. }

取最后3个

  1. /* 取最后3个
  2. -0+3=3
  3. -1+3=2
  4. -2+3=1
  5. -3+3=0 不可用
  6. 因为是倒着数的所以从底部开始
  7. */
  8. .list > li:nth-last-of-type(-n + 3) {
  9. background: chocolate;
  10. }

取奇数

  1. /* 取奇数 */
  2. /* 2*0+1=-1
  3. 2*1+1=3
  4. 2*2+1=5
  5. 2*3+1=7
  6. ... */
  7. .list > li:nth-of-type(2n+1) {
  8. background: chocolate;
  9. }
  10. /* 简写
  11. .list > li:nth-of-type(odd) {
  12. background: chocolate;
  13. }
  14. */

取偶数

  1. /* 取偶数 */
  2. /* :nth-of-type(2n) 可以直接简写even */
  3. .list > li:nth-of-type(even) {
  4. background: chocolate;
  5. }
批改老师:PHPzPHPz

批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学