I think the fact that ::selection is in both rules is throwing you off a little. Youâre basically wiping out the first statement with the second (for the generic âselectionâ anyhow).
Maybe someone can beat me to it, but a simple way (in the editor) to change the selection in code blocks is
Anything not in code blocks is âhighlightedâ as usual.
In preview there is an added class, so itâs a bit to tricky for me to delve into at the moment. IIRC the rule is that ::selection usually has to be on a parent element, and not a class.
CodeMirror doesnât really select anything: it fakes it by creating a highlight in the background of the text. You can style that highlight shape, but you canât use that to change the styling of the text, only the background layer underneath the text.
The latest version of CodeMirror (used on Obsidian mobile and eventually Obsidian desktop) does allow using the ârealâ selection (via content-editable), but even that only applies for single selection, not multiple selection. Multiple selection is still emulated via a background highlight layer even in CodeMirror 6.
tl;dr: target your CSS at CodeMirrorâs background selection layer, not the ::selection, as CodeMirror doesnât use the browser for text selection. (Well, it may do it in its invisible textarea, I suppose.)
Thanks for that answer, it pointed me back to this answer on Stack Overflow, which now makes more sense to me. I now use this for edit mode (not with red of course):
.CodeMirror-selected {background:red !important;}
And as mentioned before, the other selectors do work for preview mode.