Overlay Page Content Except One Element

Posted by

When it comes to site tours or tutorials, it is a good practice to overlay page content except the element that users should pay attention to. This effect is popular today and implemented in a variety of sites and apps.

An example picture for the overlay usage

CSS

There are two steps to take in order to implement this design.

  1. Cover over page content with overlay
  2. Bring an element up to the front layer

Overlay Page Content

Create an element that stretches over page content. You can achieve it by setting up an element that is out of the document flow: { position: fixed; } or { position: absolute; }. The use of ‘position absolute’ can be preferred if you only want the overlay to be over the parent element whose position is set relative. Make sure that you set z-index that is higher than the elements you want to cover.

.overlay {
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Bring an element to the front

Everybody knows z-index can control the stacking order of elements. However, it is not that simple because there are rules over how elements stack on each other depending on circumstances. In this case, everything except the overlay element is in the normal flow of the document. It means that no matter how high z-index is set on those elements, it doesn’t work. Here is a detailed explanation about this phenomenon.

So, what do we do to get z-index working? Setting an element’s position to relative. That way, it will essentially stay out of the normal flow and z-index will work. If the overlay is a sibling before the element, the same z-index value of 1 can bring the element to the front. It is because an element after will always be on top of the stacking order.

.visible {
  position: relative;
  z-index: 1;
}

CodePen

Here is an example code on CodePen.

Thanks for reading.

Hope you enjoyed the article. If you have any question or opinion to share, feel free to write some comments.

Facebook Comments