Changing the Selection Colors in HTML
This CSS 3 (cascading style sheet) feature is incredibly simple to implement, but can provide your HTML pages a very unique look and helps your site stand out from the general crowd. With everything that we can do with CSS now a days, this trick can add a huge boost to the entire sites theme and help tie the entire site together with very little effort.
The fiddle is created here.
body {
color:#284A66;
background: #F9F9F9;
font-family: Arial;
padding:10px;
}
With the body of the page styled with the above CSS - where the style sets the font color to #284A66 (a Blue Gray color), background color to #F9F9F9 (a Light Gray shade) and sets the font as Arial and provides padding to all sides of the page to 10px, the page and its default selection will look as below:
To change the selection color, we need to use CSS 3 pseudo-element ::selection
as below:
::selection {
color: #0BB7F5;
background: #B6E9FC;
}
Here, the font color is set to #0BB7F5(a Sky blue color) and the selection/background color is set to #B6E9FC(a Light blue color).
::-moz-selection {
color: #0BB7F5;
background: #B6E9FC;
}
A Mozilla Firefox version of the pseudo-element is also set.
.highlight {
color:white;
background:#EC1455;
}
.highlight::selection {
color: #0BB7F5;
background: white;
}
.highlight::-moz-selection {
color: #0BB7F5;
background: white;
}
A CSS class .highlight
is used to highlight some key phrases, which is applied to spans on the page. A different selection color scheme of white and light blue is used for the highlight
class.
This shows that the ::selection
pseudo-element can be combined with different elements on the page.
.highlight:hover {
color:#8E1237;
background:#EC1455;
}
Here, I have also added the pseudo-element :hover
for the .highlight
class, which changes the color schema of the highlight span
when mouse hovers over it.
The page now looks as below. It's nothing fancy, but in a good designers hands, it can create pure magic.
The final result with all the style and with the text selection looks as below. It can be seen that the span
s with highlight
class have a different color scheme.
All the screen shots are from Mozilla Firefox. Chrome and Safari will not produce an opportune selection color for the highlight class - Excuse given: The pseudo-element ::selection
, is not well documented in the CSS 3 specification!
And finally a real shocker, Internet Explored 8 and 9 produce the result as expected!!!
Happy coding...