I have just discovered and learnt about a CSS3 pseudo element I’d never previously come across. The ::selection pseudo element.

I stumbled across it when visiting Dan Mall’s excellently designed site. I accidentally highlighted some text and the background went green with the text turning white. I was intrigued, what kind of sorcery was this.

It was the little used ::selection pseudo element that used to be in the CSS3 draft. Unfortunately, it has been removed for reasons I currently do not know. I am hoping that it gets put back in some time in the future but luckily, for the experimenters out there, it wasn’t removed until after the modern browsers had chance to implement it. Therefore we can give it a go!

To use it in your projects you can add some CSS like this:

::selection {
    background: #ccc;
}

Alternatively, to get it to work in Firefox you will need to use the -moz browser prefix:

::-moz-selection {
    background: #ccc;
}

Although there is no guarantee it will be put back into the spec neither Mozilla or the Webkit workers have any intention of removing their implementations. It’s already done, is pretty stable so there is no need to remove it. Therefore we are free to use it if we want and to me that is fine. It is a simple example of Progressive Enhancement and using it will in no way adversely affect anyone not using a browser that supports it.

As far as I am aware the browser implementations currently only support the color and background properties even though the original recommendation from the W3C included optional cursor and outline properties. To get an example of what can and can’t be done with it you should have a look at this useful test page.

I have now implemented it on this blog, putting it all together like so:

.post-content p::selection,
.page-content p::selection {
	background: #489BD5; /* safari */
	color: #fff;
}

.post-content p::-moz-selection,
.page-content p::-moz-selection {
	background: #489BD5; /* firefox */
	color: #fff;
}

What do you think of this? Should it be put back in the spec or are you glad it’s gone?