Window Inactive Styling

Avatar of Chris Coyier
Chris Coyier on

You can customize the text color and background color of text when it’s selected with ::selection and ::-moz-selection. We’ve covered that a number of times here in various forms and it’s a cool little trick.

Even the HTML5 Boilerplate has it in there by default, using super hot pink, which is the easiest way to spot a boilerplate site =).

But when you change text selection styling away from its default, you lose the default styling’s ability to desaturate itself when the window goes out of focus. See:

I rather like how the default desaturates and becomes less visually intense. After all, chances are you are focused on another window right now and don’t need a background window fighting for attention.

Perhaps a little known fact, but you can use a pseudo selector in conjunction with ::selection to apply styling when the window is in it’s inactive state. It uses the :window-inactive pseudo selector, like this:

::selection {
  background: hsl(136,65%,45%);
  color: white;
}
::selection:window-inactive {
  background: hsl(136,25%,65%);
}

Using HSL for color value there, I was able to lower the saturation and increase the lightness to get a less intense version of the same hue.

Remember Firefox has it’s own version of ::selection, ::-moz-selection. It also has it’s own version of :window-inactive, :-moz-window-inactive. Unfortunately using these things together doesn’t work.

/* Does work */
::-moz-selection {
  background: rgba(255,0,0,0.9);
  color: white;
}
/* Doesn't work */
::-moz-selection:-moz-window-inactive {
  background: rgba(255,0,0,0.3);
}
/* Nor this */
:-moz-window-inactive::-moz-selection {
  background: rgba(255,0,0,0.3);
}

So anyway, you can at least get a custom text selection color in Firefox (3.6+ ?) but you can’t style it specially for window inactive. However, Firefox (3.6 and 4 tested) automatically make your text selection gray on when the window is out of focus.

It’s important to note that it’s not because :-moz-window-inactive doesn’t work, it does, you can use it on any element, actually, like making a div change background color in that state. It’s just using them together that doesn’t.

This is not a case where we can shake our fists at the browser vendors. None of this is standardized. ::selection isn’t standard. :window-inactive isn’t standard. In fact, ::selection is actually technically a pseudo element not pseudo selector so it should have to come last in the selector, but if you switch them around it doesn’t work.

More than just text selection

If :window-inactive was standardized and more widely supported, you could do way more with it than just deal with text selection colors. Think of gray-scaling a whole website or stopping animations.