且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不更改默认颜色和背景颜色的情况下使用CSS3 :: selection?

更新时间:2023-01-15 09:20:37

由于这个选择器没有官方支持CSS,正在从CSS3中移除,目前尚未在CSS4草稿中,确实没有太多关于如何应用选择器的文档。



如选择器所定义,它意味着覆盖系统的默认文本选择颜色。浏览器显然是从字面上。通过指定 :: selection ,即使没有指定它们,这些颜色也会立即被覆盖。问题是系统的默认值不是CSS的一部分。浏览器正在查看您的声明,并认为忽略系统的默认值,而是使用此声明中的内容。因为你没有指定颜色,没有应用颜色(背景是无,颜色是继承的)。



这只是一个有关出现的原因的理论,因为我说,实际上没有关于实际发生或应该发生什么的文档。



老实说,你真正知道的唯一方法是看看在源代码,看到它在做什么,当它看到的选择器。也许要求开发团队中的一个浏览器的人更容易。任何一种方式仍然是困难的。也许你可以提交一个错误报告,他们可以更深入地探讨这个问题...


The following lines are included in the HTML5 Boilerplate template by default:

::-moz-selection{background:#fe57a1;color:#fff;text-shadow:none;}
::selection{background:#fe57a1;color:#fff;text-shadow:none;}

However, I want to keep the selection color as the OS default (blue in Windows, I think it's brownish orange in Ubuntu). If I leave out the background property, there will be no background.

Since this selector is not officially supported for CSS, being removed from CSS3 and not currently in the draft for CSS4, there really isn't much documentation on how exactly the selector should be applied.

As defined by the selector, it is meant to override the system's default text selection colors. The browsers have apparently taken this literally. By specifying ::selection, those colors are immediately overwritten, even if you haven't specified them. The problem is the system's defaults are not part of CSS. The browser is seeing your declaration and thinking "ignore the system's default, use what's in this declaration instead." Since you don't have colors specified there, no colors are applied (background is none and color is inherit). Whoops, kind of hard to tell your text is selected, huh?

This is only a theory of what appears to be happening since, as I said, there really is no documentation on what actually happens, or what is supposed to happen.

Honestly, the only way you'd really know for sure is to look at the source code and see what it's doing when it sees that selector. Maybe asking someone on the development team for one of these browsers would be easier. Either way would still be difficult. Maybe you could submit a bug report and they can delve into the issue a little more...