June 11, 2020
How to Change Selected Text Background Color in CSS
::selection pseudo element can be used to apply any set of CSS props to the highlighted portion of the document. It is widely supported by all modern browsers, but there are few older browsers which do not support it such as IE6-8, Opera mini etc. You can get complete list of supported browsers here. HTML, CSS and Javascript code is given below.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>This is H1 Element</h1> <p>This is paragraph Element</p> <div>This is DIV Element</div> </body> </html>
CSS:
body { display: flex; flex-direction: column; align-items: center; } h1, p, div { border: 1px solid black; padding: 10px; } /* p::selection { background-color: black; color: #fff; } div::selection { background-color: yellow; color: red; } */ ::selection { background-color: yellow; color: red; }
HTML: