How to Change Selected Text Background Color in CSS

How to Change Selected Text Background Color in CSS

In this article you will learn how to change background of selected text using html and css. Changing select text color is very easy which you can do with just 1 line of css.

Change text highlight color CSS is a method by which you can change the Selected Text Background Color of any text in your website. 1 line of css is enough to change the default text selection color.

How to Change Selected Text Background Color in CSS

When you select a text or heading in your website, its background color can be seen. Blue color is visible by default in the website. You will know how to customize that color from this article.

You can change Selected Text Background Color of any page by ::selection. Use p::selection if you only want to change the selected background color of the paragraph.

Similarly, you can use h2::selection to change the selected background color of h2.

Selected Text Background Color in CSS

To change the background color of selected text in CSS, you need to use the ::selection pseudo-element. The ::selection pseudo-element applies styles to the text that is currently selected by the user.

See the Pen Selection Style by Ground Tutorial (@groundtutorial) on CodePen.

Here I tried to explain you very simply how to change Selected Text Background Color by css. 

Here I have given a simple design where I have used one heading and one line of text. I used different Selected Text Background Color for both heading and text.

1. Selected Text Background Color HTML

The first step in changing the background color of selected text in CSS is to add the HTML markup that you want to format. For example, you can add a section of text to your HTML file like this:

				
					<h1>Select Me</h1>
<p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Modi similique

</p>
				
			

2. Selected Text Background Color CSS

Now we will change the default text selection color by CSS. You can use ::selection to add a custom Text Selection Color.

When you use ::selection it will apply to all content. You can use p::selection if you want it to apply only to paragraphs.

If you want to change the Default Text Selection Color of the heading then you can use h2::selection.

				
					::selection {
    background: #8222ff;
}

p::selection {
    background: #ff9514;
    color: #000;
}

body {
    background: #080b10;
    color: #ffff;
    font-family: "Poppins", sans-serif;
    max-width: 500px;
    margin: 0 auto;
    height: 100vh;
    display: grid;
    place-content: center;
}

p {
    font-size: 1.1rem;
}
h1 {
    margin-block-start: 0;
    margin-block-end: 0;
}
				
			

Hope from this article you have learned how to change Default Text Selection Color and add Custom Selected Text Background Color.

If you have any question related to CSS then you can comment me. Comment how you like this Default Text Selection color changing tutorial.