Using CSS3 text-selection to override default highlight colour blog post

Using CSS3 text-selection to override default highlight colour

Todd Motto

9 Apr, 2012

JavaScript

1 minute read

Add something different to your website by overriding the default text selection colour (boring blue and no text styling) when highlighting words/images on your website. Check out the demo below by highlighting the paragraphs, and add the code to your own website.

Note: Will not work in IE6-8, but you’re good on Safari/Chrome (WebKit), Mozilla FireFox (Gecko) and IE9+

Here’s the code to add to your CSS to implement your default text selection colour.

CSS (Global Colour Change)

/* IE9  - Also picked up by most modern browsers */
::selection {
  background:#AC2937;
  color:#FFF;
  text-shadow:none;
}
/* Safari & Chrome - Webkit Rendering */
::-webkit-selection {
  background:#AC2937;
  color:#FFF;
  text-shadow:none;
}
/* Mozilla based - Gecko Rendering */ 
::-moz-selection {
  background:#AC2937;
  color:#FFF;
  text-shadow:none;
}

HTML

If you want to highlight different paragraphs, you can target individual elements like so:

<!-- Green Paragraph -->
<p class="green-select">Your paragraph text here.</p>

CSS (Specific Area Colour Change)

/* Green Paragraph Custom Selection Colours */
.green-select::selection {
  background:#009E30;
  color:#FFF;
  text-shadow:none;
}

.green-select::-webkit-selection {
  background:#009E30;
  color:#FFF;
  text-shadow:none;
}

.green-select::-moz-selection {
  background:#009E30;
  color:#FFF;
  text-shadow:none;
}

Once you've finished reading this post, do you want to learn even more?

javascript

Learn JavaScript for FREE!

We've created the best online course for you to fully master JavaScript using real-world examples and techniques you’ll find nowhere else.

  • ES2015 and beyond
  • Variables and Scoping
  • Strings, Numbers and Booleans
  • Conditional Statements
  • Operators
  • Modules
  • Arrays and Objects
  • Functions and Closures
  • Loops and Iteration
Get course Get javascript Basics

About the author

Todd Motto profile picture

Todd Motto

GDE Google Developer Expert

Todd is the Founder of Ultimate Courses. With a passion for Angular, TypeScript and JavaScript, Todd leads the online courses creation and has written hundreds of articles on front-end web development and beyond. He specialises in breaking down complex topics and understands the critical mission of learning new technology fast, comprehensively and the right way.

Love the post? Share it!

Lots of time and effort go into all our blogs, resources and demos,
we'd love it if you'd spare a moment to share them!

Explore our JavaScript courses

Get started today and join over 60,000 developers.