Serg Hospodarets Blog

Serg Hospodarets blog

Highlight an element with page fading on pure CSS Serg Hospodarets Blog

Sometimes to highlight something we need to fade entire page except element/part which we want to focus.

Examples

Usual way to implement

Usually people provide such effect using 4 “fade” divs technique:

  1. Page without highlighting
  2. Highlight with 4 black faders
  3. Color faders to visualize them

This technique has many problems like:

  • You cannot use border-radius for highlighted area. It’s possible to implement but it will add complexity to implementation.

  • Have to use or write JavaScript plugins for adding these 4 faders and place them in correct places around highlight element. Also there should be event listeners on page resize to change faders size.

  • Possible problems with appearing and position of page scroll- to show faders or before they change size (after window resize event).

Proposed technique (without JavaScript)

Fade the page except element area

To avoid using faders elements and provide shadow from element- of course, the best to use box-shadow which was provided exactly for such things.

.highlight {
    box-shadow: 0 0 0 99999px rgba(0, 0, 0, .8);
}

For old browsers (like IE < 9) you can use CSS3 Pie or old IE filter property

To move element to front on Z-axis (over all others) you can provide:

.highlight {
    position: relative;
    z-index: 9999;
}

Prevent any user actions outside of highlighted area

Usually when spotlight focus is set to some element- it’s needed to stop interaction with parts under fader. E.g. prevent default browser behavior when user clicks links, submit forms etc. In short- we need to emulate behavior when our fader is at top of all the page elements (except highlighted area).

In that it’s possible to use pointer-events property which allows to control under what circumstances a particular graphic element can become the target of mouse/touch events. It means, you can prevent any user actions for any part of your application.

body.highlight-is-active {
    pointer-events:  none;
}

.highlight {
    pointer-events:  auto;
}

Pointer-events (for HTML) has not bad browser support, if you need to provide it in old browsers- use Pointer Events Polyfill

Demo

Finally wrapping all together:

  1. Pure CSS solution without any listeners of page resize or problems with scroll

  2. Working with border-radius for highlighting area

  3. Effects for fader appearing using css transition

  4. Disabling highlighting on click out of highlighted area

Provide your code in <pre><code></code></pre> tags