Color: inherit; not working with :: select in IE or EDGE

I have a page that uses CSS by default to set background-color to gray and color to black.

Now, for part of the webpage, I want to keep color when selecting text. I tried to override the CSS for this part using color: inherit; . It worked in Chrome and Firefox, but did not work for IE and EDGE.

I created a small example to explain my problem:

 ::selection { color: #000; background: #c6c6c6; } ::-moz-selection { color: #000; background: #c6c6c6; } .p1 { color: red; } .p2 { color: green; } .override ::selection { color: inherit; } .override ::-moz-selection { color: inherit; } 
 <div> <p>Heading 1</p> <div class="override"> <p class="p1">Sub heading 1</p> <p class="p2">Sub heading 1</p> </div> </div> 

I want to keep color for the html part with class overrides, and I cannot change the default CSS.

JS Fiddle Link: https://jsfiddle.net/h30jczkv/1/

+5
source share
1 answer

This does not work because it is not supported in IE

IE does not support inherit when styling a pseudo-element ::selection :

The style properties in the :: selection pseudo-element do not support the value "inherit".

:: Pseudo-element of choice ( https://msdn.microsoft.com/en-us/library/jj127349(v=vs.85).aspx )

You can do the following to get a similar result

The desired behavior can be achieved without using inherit using the :not() pseudo- inherit , although it will require some small changes to the HTML. The principle of this is that:

  • You override the background-color for all elements with ::selection {background: #c6c6c6;}
  • Move the override class to the p elements themselves
  • You override color for all elements except those that have a .override class with :not(.override)::selection{color: #000;}
  • .p0{color: blue;} to show that the change is working

I do not think that this behavior can be obtained without changing the HTML, since the :not() class pseudo-class accepts a simple selector .

 ::selection { background: #c6c6c6; } :not(.override)::selection { color: #000; } .p0 { color: blue; } .p1 { color: red; } .p2 { color: green; } 
 <div> <p class="p0">Heading 1</p> <div class="override"> <p class="p1 override">Sub heading 1</p> <p class="p2 override">Sub heading 1</p> </div> </div> 

JS script example

Alternatively, you can achieve this without modifying the HTML

If all the classes you want to override start with p , you can use the attribute selector [foo^="bar"] :

 ::selection { background: #c6c6c6; } :not([class^=p])::selection { color: #000; } .t1 { color: blue; } .p1 { color: red; } .p2 { color: green; } 
 <div> <p class="t1">Heading 1</p> <div class="override"> <p class="p1">Sub heading 1</p> <p class="p2">Sub heading 1</p> </div> </div> 

JS script example

+2
source

Source: https://habr.com/ru/post/1240635/


All Articles