skip to Main Content

I use an HTML page to render some console output. The content of this page is pretty simple:

<div>
    <span style="color: #0cc;">Checking random configurations</span><br>
    <span style="color: #0cc;">Installing new setup</span><br>
    ...<br>
    <span style="color: #0cc;">Done setup</span><br>
    <span style="color: #0cc;">Start</span><br>
    <span style="color: #c00;">ERROR</span><br>
    done.
</div>

I would like to customize the way the selected text is highlight (user selected text using the mouse) so that the foreground color becomes the background color and the background color becomes the foreground color.

I could not manage to find my way using CSS highlight property which sets the color to be used for highlighting the whole selection.

Is there a simple and portable way (HTML and/or CSS and/or java-script) to make the highlight color change regarding the current text’s foreground and background colors?

EDIT:

The rendered text can be styled in multiple ways. As you can see in the example, some text is red, some other cyan, .. and many other formats are not given in the example.

From the user point of view, I would like the text selection highlight to be adapted to the selected text (i.e.: the portion of red text should be highlighted red/black (fg/bg), the later portion of cyan text should be highlighted cyan/black).

The ::selection let me select the highlight FG and BG color but this is for the whole section. How can I embed it into the span so that I can customize the highlight on a per-portion basis?

2

Answers


  1. You could simplify things by having CSS variables set where they need to be and on selection just exchange the color and background colors:

    <style>
      span {
        --bg: black;
      }
      
      span {
        color: var(--color);
        background: var(--bg);
      }
      
      span::selection {
        background: var(--color);
        color: var(--bg);
      }
    </style>
    <div>
      <span style="--color: #0cc; --bg: pink;">Checking random configurations</span><br>
      <span style="--color: #0cc;">Installing new setup</span><br> ...
      <br>
      <span style="--color: #0cc;">Done setup</span><br>
      <span style="--color: #0cc;">Start</span><br>
      <span style="--color: #c00;">ERROR</span><br> done.
    </div>

    Note: this is not a total solution because I’ve just used a blanket white for background where it isn’t explicitly defined. Given the very small set of properties that can be set on a ::selection pseudo element I cannot at the moment see how to pick up an inherited or existing background color using only CSS. But I leave this part-answer here in case it is at least partly useful.

    Login or Signup to reply.
  2. diminta oleh pemimpin saudara untuk membantu project yang sedang ditangani. Yaitu membawa web responsive dengan css.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search