I have a page where the default text selection CSS is applied to set background-color
to grey and the color
to black.
Now, for a part of web page I want to preserve the color
on text selection. I tried overriding the selection CSS for that part by using color: inherit;
.
It worked for Chrome and Firefox but didn't work for IE and EDGE.
I have 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 preserve color
for the part of html with the class override and I can't change default selection CSS.
JS Fiddle link: https://jsfiddle.net/h30jczkv/1/
IE does not support inherit
when styling the ::selection
pseudo-element:
Styling properties on the ::selection pseudo-element do not support the "inherit" value.
::selection pseudo-element (https://msdn.microsoft.com/en-us/library/jj127349(v=vs.85).aspx)
The desired behaviour can be achieved without using inherit
by using the :not()
pseudo-class, although it will require some slight modifications to HTML. The principle behind this being that:
background-color
for all elements with ::selection {background: #c6c6c6;}
override
class onto the p
elements themselvescolor
for all elements except those with the class .override
with :not(.override)::selection{color: #000;}
.p0{color: blue;}
added to show that the change is workingI don't think this behaviour can be obtained without modifying the HTML as the :not()
pseudo-class only accepts simple selectors.
::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 Fiddle Example
If all the classes you want to override begin with p
you could use the [foo^="bar"]
attribute selector:
::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 Fiddle Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With