今天在论坛 , 有看到这样一道非常有意思的题目 , 简单的代码如下:
<div><p id="a">First Paragraph</p></div>
样式如下:
p#a {color: green;}div::first-line {color: blue;}
试问 , 标签 <p>
内的文字的颜色 , 是 green 还是 blue 呢?
有趣的是 , 这里的最终结果是蓝色 , 也就是 color: blue
生效了 。
![两道超有意思的 CSS 面试题,试试你的基础](http://shimg.jingyanzongjie.com/230724/1542534314-0.png)
文章插图
不对 , 正常而言 , ID 选择器的优先级不应该比伪类选择器高么?为什么这里反而是伪类选择器的优先级更高呢?
并且 , 打开调试模式 , 我们定位到
<p>
元素上 , 只看到了 color: green
生效 , 没找到 div::first-line
的样式定义:![两道超有意思的 CSS 面试题,试试你的基础](http://shimg.jingyanzongjie.com/230724/15425312b-1.png)
文章插图
只有再向上一层 , 我们找到
<div>
的样式规则 , 才能在最下面看到这样一条规则:![两道超有意思的 CSS 面试题,试试你的基础](http://shimg.jingyanzongjie.com/230724/1542532H2-2.png)
文章插图
因此 , 这里很明显 , 是
<p>
标签继承了父元素 <div>
的这条规则 , 并且作用到了自身第一行元素之上 , 覆盖了原本的 ID 选择器内定义的 color: green
。再进行验证这里 , 另外一个比较迷惑的点在于 , 为什么 ID 选择器的优先级比
::first-line
选择器更低 。我们再做一些简单的尝试:
下面的 DEMO 展示了
::first-line
样式和各种选择器共同作用时的优先级对比 , 甚至包括了 !important
规则:- 第 1 段通过标签选择器设置为灰色
- 第 2 段通过类选择器设置为灰色
- 第 3 段通过 ID 选择器设置为灰色
- 第 4 段通过 !important bash 设置为灰色
::first-line
选择器 。<h2>::first-line vs. tag selector</h2><p>This paragraph ...</p><h2>::first-line vs class selector</h2><p class="p2">This paragraph color i...</p><h2>::first-line vs ID selector</h2><p id="p3">This paragraph color is set ...</p><h2>::first-line vs !important</h2><p id="p4">This paragraph color is ....</p>
p {color: #444;}p::first-line {color: deepskyblue;}.p2 {color: #444;}.p2::first-line {color: tomato;}#p3 {color: #444;}#p3::first-line {color: firebrick;}#p4 {color: #444 !important;}#p4::first-line {color: hotpink;}
CodePen Demo -- ::first-line: demo看看效果:
![两道超有意思的 CSS 面试题,试试你的基础](http://shimg.jingyanzongjie.com/230724/1542533561-3.png)
文章插图
可以看到 , 无论是什么选择器 , 优先级都没有
::first-line
高 。究其原因 , 在于 ,
::first-line
其实是个伪元素而不是一个伪类 , 被其选中的内容其实会被当成元素的子元素进行处理 , 类似于 ::before
, ::after
一样 , 因此 , 对于父元素的 color 规则 , 对于它而言只是一种级联关系 , 通过 ::first-line
本身定义的规则 , 优先级会更高!这也是为什么 , 在 MDN 文档中 , 更推荐的是双冒号的写法(当然浏览器都支持单冒号的写法)-- MDN -- ::first-line
![两道超有意思的 CSS 面试题,试试你的基础](http://shimg.jingyanzongjie.com/230724/1542535221-4.png)
经验总结扩展阅读
- 葛小伦和彦的结局
- 高马尾 韩国超模崔素拉登西班牙《VOGUE》封面,单人单抗!
- 毛呢大衣爱沾毛怎么办
- 丰巢快递柜超过一天快递怎么取
- 苹果手机怎么使用超级截屏(苹果手机超级截屏在哪里)
- http和https分别是什么?
- 手机超卡怎么办
- 华为手机怎么截屏(华为怎么滚动截超长图)
- 杨超越锦鲤什么梗?
- 花花万物第二季中张嘉倪买超第几集?