How to change the color and background of selected text with the mouse?

11

When we select a text with the mouse in a website the text is white and with a blue background (I think it can vary from browser to browser). But I would like to know if it is possible to change the color and background of this text with CSS only, and if it has a solution that supports the various browsers.

Here's an example of the change I'd like to make:

    
asked by anonymous 24.10.2018 / 22:55

2 answers

5

You get this effect using the ::selection pseudo-element.

The pseudo-element is supported for most browsers including IE-9 , but as of today 24/10/18 is not supported for IOS Safari nor for Opera Mini as can be seen on site Can I Use .

It would look like this:

::selection {
    background-color: red;
    color: lightgreen;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae porta purus, in tincidunt dui. Ut ut neque neque. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut porttitor convallis purus sed porttitor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac velit turpis. Integer sed dui quam. Suspendisse laoreet aliquam velit, sed interdum sapien. Donec id nisl non libero vehicula malesuada rutrum auctor ex. </p>

Note: For firefox versions

24.10.2018 / 23:06
5

You can use the css ::selection property, I made a short example to make it easier to learn.

.exemplo-background::selection {
  background: #e74c3c;
}

body {
  font-family: 'Source Sans Pro', Arial, sans-serif;
  line-height: 1.45;
  background: #E0DCCC;
  color: #333;
  padding: 1em;
  font-size: 18px;
}
<p class='exemplo-background'>Você pode alterar a cor de fundo ao selecionar esse texto.</p>

link

    
24.10.2018 / 23:08