5
votes

Issue

Using the following just simply doesn't work properly in -webkit- and -moz- browsers:

#exampleElement {
    background-color: red; /* For example */
}

#exampleElement ::selection {
    color: black;
    background-color: white;
}

 

Result: WebKit- and Blink-powered browsers

In Chrome, Opera, and Safari, ::selection's background-color renders as if it was 50% alpha but the font colour is correct.

Chrome 29.0.1547.62:
Chrome 29.0.1547.62

Opera 15.0.1147.130:
Opera 15.0.1147.130

Safari 5.34.57.2:
Safari 5.34.57.2

 

Result: Gecko-powered browsers

In Firefox, the entire ::selection rule is ignored. ::selection's background-color just happens to be white due to #exampleElement's dark background-color (thanks to @BoltClock for noticing that)

Firefox 22.0:
Firefox 22.0

 

Result: Trident-powered browsers

In Internet Explorer, (would you believe) everything is rendered perfectly.

Internet Explorer 10.0.9200.16660:
Internet Explorer 10.0.9200.16660

 

Is this just a flaw of these rendering engines / browsers or are there -webkit- and -moz- alternatives that I'm unaware of?

I've saved an example of this on jsFiddle, for people to see: http://jsfiddle.net/BWGJ2/

2
Yes, amazing as it may seem, IE9 does actually work!Niet the Dark Absol
Firefox is actually ignoring the entire ::selection rule - its default highlight background just happens to be white if it determines that the parent background is dark enough not to use blue as a background.BoltClock
@BoltClock Good spotting. I'll update my question.mythofechelon

2 Answers

4
votes

According to quirksmode.org, -webkit-selection and -moz-selection are indeed available. I just tested it with Chrome (18) and Firefox (13) and can confirm that it works with Firefox, but I didn't have success with -webkit-selection on Chrome (it ignored it), and according to this SO question it doesn't exist (and the answer says that ::selection should also work on all browser, but doesn't for me, too).

As already metioned in this answer, Chrome forces the selection to be transparent, but you can work around this using

background:rgba(255, 255, 255, 0.99);

For more details, checkout the linked answer by tw16


Furthermore, this works for me on FF:

::selection { /* stuff */ }
::-moz-selection { /* stuff */}

But this does not:

::selection, ::-moz-selection { /* stuff */ }

But maybe this is not related to ::selection but does apply on all pseudo elements, couldn't find an answer to that.

0
votes

There are browser-dependent versions. The version you're using was the standard CSS3 way, but then it got dropped from the spec. I dunno about its browser support...

And something else to consider: An ID-based CSS selector might "outweigh" a pseudoclass-based selector, resulting in the ID-based CSS always taking precedence. So try adding !important to your ::selection style to make sure it's always used when applicable.

Hope that helps!