6

周知:CSS -webkit-伪元素选择器不再导致整行无效

 4 years ago
source link: https://www.zhangxinxu.com/wordpress/2018/12/css-webkit-%e4%bc%aa%e5%85%83%e7%b4%a0-%e9%80%89%e6%8b%a9%e5%99%a8-%e6%97%a0%e6%95%88/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

by zhangxinxu from https://www.zhangxinxu.com/wordpress/?p=8300
本文可全文转载,个人网站无需授权,只要保留原作者、出处以及文中链接即可,任何网站均可摘要聚合,商用请联系授权。

一、一些已知特性

例如下面的CSS:

div, span::whatever {
  background: red;
}

其中::whatever 是随便写的一个无效的伪元素选择器。div这个选择器肯定是合法的。但是,如果它们写在一起,不好意思,所有选择器都不支持了。也就是页面上的<div>元素的背景色不会表现为红色,浏览器直接忽略这条声明。

无效的伪元素选择器导致整行选择器失效

这个特性很多人应该有注意到,甚至可以借此写一些CSS hack进行浏览器区分。

然而,更多时候,是会给我们带来烦恼,例如,我们对输入框placeholder占位符颜色进行样式重定义的时候,只能分开写(CSS取自LuLu UI):

/* for webkit/blink */
::-webkit-input-placeholder {
  transition: opacity .15s;
  color: #a2a9b6;
  line-height: inherit;
  font-size: 14px; 
}
:focus::-webkit-input-placeholder {
  opacity: 0.38; 
}
/* for firefox */
::-moz-placeholder {
  transition: opacity .15s;
  color: #a2a9b6;
  font-size: 14px; 
}
:focus::-moz-placeholder {
  opacity: 0.38; 
}
/* for IE10+/Edge */
:-ms-input-placeholder {
  transition: opacity .15s;
  color: #a2a9b6 !important;
  font-size: 14px; 
}
:focus:-ms-input-placeholder {
  opacity: 0.38; 
}

我们不能合起来写,例如:

::-webkit-input-placeholder,
::-moz-placeholder,
:-ms-input-placeholder {
  color: #a2a9b6;
}

结果输入框占位符颜色没有变成希望的#a2a9b6,而是默认的#757575,因为合在一起大家都无效了,要死一起死,就是这么回事。

颜色没有生效

二、现在的变化

现在,浏览器约定俗成,开始有了一些变化,具体变化内容如下,来自MDN文档

通常,如果选择器链或组中有无效的伪元素或伪类,则整个选择器列表无效。如果伪元素(但不是伪类)具有-webkit-前缀,那么对于Firefox 63+,Blink、Webkit和Gecko浏览器认为它是有效的,而不会使选择器列表无效。

什么意思呢,开始一开始的例子,我们随便写一个伪元素选择器,但是,使用-webkit-私有前缀,如下:

div, span::-webkit-whatever {
  background: red;
}

结果,此时,div可以正常选择器渲染,如下示意:

div背景色是红色

浏览器对这一行CSS选择器的解析结果如下:

浏览器的选择器解析截图

也就是虽然span::-webkit-whatever表现为不支持(灰色),但div依然正常解析(黑色)。

此特性变化是Firefox 63之后才有的变化,Nice变化。

不过坏消息是IE浏览器依然不承认::-webkit-这一套,好在Edge已经官宣以后用Chrome那套内核了,虽然不知道猴年马月,但有希望总比时刻失望的好。

参考文章

感谢阅读,欢迎交流!

1f603.svg

(本篇完)1f44d.svg 是不是学到了很多?可以分享到微信
1f44a.svg 有话要说?点击这里


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK