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

Asked

Viewed 913 times

10

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

An example of the amendment I would like to make:

inserir a descrição da imagem aqui

  • 2

    That’s all ::selection

  • But only with this pseudo-element will the effects be applied in all browsers?

  • From: Chrome 4.0, IE 9.0, Firefox 2.0, Safari 3.1, Opera 10.1. Since for Firefox it is necessary to use the prefix -Moz-

  • Maybe this link can help you: https://css-tricks.com/overriding-the-default-text-selection-color-with-css/

  • 1

    @Leandrade Show mano! Thanks for the warning, it is of great help!

  • @Mikeotharan very good link content! Thank you for sharing!

Show 1 more comment

2 answers

5


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

The pseudo-element has support for most browsers including IE-9, but on today’s date 24/10/18 there is no support for the IOS Safari nor for the Opera Mini as can be seen on the 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>

Obs: For <=61 versions of firefox, you need to use the following syntax:

::-moz-selection

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/:Selection

  • Thanks for the example and the tips regarding Jorge browsers!

4

You can use the property css ::selection, made a brief example to facilitate in learning.

.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>

https://codepen.io/anon/pen/mzQLyO

  • Thanks for the example André! Very good!

  • Thanks @Joãopedroschmitz, hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.