前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(2019)[前端]面试题[7]:CSS中权重计算方式方法

(2019)[前端]面试题[7]:CSS中权重计算方式方法

作者头像
无道
发布2019-11-13 16:41:39
1K0
发布2019-11-13 16:41:39
举报
文章被收录于专栏:无道编程无道编程

问题

CSS中的选择器权重

Hello,欢迎来到我的博客,每天一道面试题,我们共同进步。

解答

不用说,CSS权重肯定是面试中最常考的题之一。

我们直接上权重计算规则:

  1. 第零等:!important,是觉得的大佬,排第一。
  2. 第一等:代表内联样式,如: style=””,权值为1000。
  3. 第二等:代表ID选择器,如:#content,权值为0100。
  4. 第三等:代表类,伪类和属性选择器,如.content,权值为0010。
  5. 第四等:代表类型选择器和伪元素选择器,如div p,权值为0001。
  6. 第五等:通配符、子选择器、相邻选择器等的。如*、>、+,权值为0000。
  7. 第六等:继承的样式没有权值。

补充知识: 1、伪类: 类似于::first-child,last-of-type 这称之为伪类。 CSS3给出定义: The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors. 【伪类存在的意义是为了通过选择器,格式化DOM树以外的信息以及不能被常规CSS选择器获取到的信息。】 2、伪元素: 类似于:::before,::after ,::selection,::first-line,::first-letter 【直观区别是他两:个数不同】 CSS3给出定义: Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content). 【伪元素可以创建一些文档语言无法创建的虚拟元素。比如:文档语言没有一种机制可以描述元素内容的第一个字母或第一行,但伪元素可以做到(::first-letter、::first-line)。同时,伪元素还可以创建源文档不存在的内容,比如使用 ::before::after。】

计算规则

!important 和内联样式style都属于不讲理的那种,

  • 只要存在 !important!important便具有最高优先级;
  • 如果不存在 !important,存在style,那么style便具有最高优先级;
  • 剩下的 “ID” 、 “类,伪类和属性” 、 “元素类型和伪元素“ 分别对应 权重值(0-a-b-c)中的 a/b/c;计算方法

其余某个选择的权重,就是他们有的选择器的权重相加,相同的话后面的覆盖前面的。

比如:

代码语言:javascript
复制
*               /* a=0 b=0 c=0 -> specificity = 0-0-0-0 */
LI              /* a=0 b=0 c=1 -> specificity = 0-0-0-1 */
UL LI           /* a=0 b=0 c=2 -> specificity = 0-0-0-2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity = 0-0-0-3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity = 0-0-1-1 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity = 0-0-1-3 */
LI.red.level    /* a=0 b=2 c=1 -> specificity = 0-0-2-1 */
#x34y           /* a=1 b=0 c=0 -> specificity = 0-1-0-0 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 0-1-0-1 */

以上复制自:https://segmentfault.com/a/1190000016924975,大概就是这意思

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题
  • 解答
  • 计算规则
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档