Selection of the fittest

Select the text above to see a custom ::selection effect

Selecting content on a web page - whether by mouse, touch, gesture or stylus - always precedes copying or editing it. Content is highlighted in a light blue by most browsers by default, but CSS provides a way of customizing this:

::selection specifies the way that selected elements appear. Like ::visited, it can only affect the value of a few properties: color, background (or separately, background-color and background-image) and text-shadow. For example, this will change the background of every selected element to red:

::selection { background: red; }

::selection can also be limited to certain elements: in the following example, the appearance of <h1> elements changes during selection.

h1::selection { background: red; }

Do make sure that if you are changing the ::selection background that you preserve the text contrast ratio; the browser will not do this automatically for you. As an example, for black text with a dark ::selection background, change the selected text to white:

h1::moz-selection { background: black; color: white; }
h1::selection { background: black; color: white; }

An interesting variation was used by Viljami Salminen, one shown at the top of this article: reversing the color, but keeping the ::selection background transparent, and stroking the outline of the text. Since only Webkit-derived browsers support text-stroke, we have to cover Firefox first:

h1::-moz-selection {
  text-shadow: -1px -1px 0 #000, 1px -1px 0 #000,
	 -1px 1px 0 #000, 1px 1px 0 #000;
  background: transparent;
}

Then, the special declaration for Chrome, Safari and Opera:

h1::selection {
   text-shadow: none;
    -webkit-text-stroke: 1px #000;
  background: transparent;
}

::selection can also be paired with the window-inactive state to determine how the selected content should appear when the browser window loses focus:

::selection:window-inactive {
  background:rgba(0,0,0,0.3);
}

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/LZxEvX