The code is very simple, but there are a few things to be aware of when using this technique.
First, you need to make sure that the overlay is positioned absolutely with respect to the body. So, if the overlay is contained in another div for example and that other div has a position set to relative, then the overlay will be positioned absolutely with respect to its container, not the page body. So you have to either let the overlay be a direct child node of the body, or make sure none of its ancestors has a position set to relative.
Also, you need to make sure the content of the page expands down to the bottom of the viewport or more, because the body expands to fit the height of its content (assuming the content is not positioned absolutely, of course), and if there isn’t enough content to expand the body height to the bottom of the viewport, then the overlay, which is getting 100% the height of the body, won’t reach the bottom of the viewport either, and so it won’t be covering it.
To avoid this, and not have to worry about the amount of content on the page, and still get an overlay which covers the entire viewport size, you should set a height on the root html element and the body. There is another thing to remember, though, when you set a height on the html and body elements:
If you give the html element a height of 100% (100% height relative to the viewport), and give the body a 100% height too (which is computed relative to the root html), then you’re setting the height of both of them to be 100% the height of the viewport, and so, no matter how far down the content of the body extends, their height remains equal to that of the viewport, and so will the height of the overlay. In this case, if you scroll down the page, the overlay will scroll up and you’ll see the content below it without an overlay, as if the overlay’s been cut off.
The solution here is to set a minimum height on the root element and on the body instead of setting a height value, which is preferable in most situations. By setting a minimum height, you’ll make sure that their height reaches the bottom of the viewport, and increases as the content increases. And lastly, to make the overlay’s height increase and have it expand to cover all the content on page scroll, you must set a position:relative; on the body so that the overlay’s height expands as the body’s height expands.
Another thing to note about this technique is not to use unnecessarily high z-index values. A lot of developers tend to use very high z-index values like z-index: 999999; when they position an overlay, or any other element, on top of other elements on a page. This is not necessary. Most of the times a z-index value of 10, or sometimes even less, is more than enough to keep an element on top of others on the page. You just need to know if there are other elements getting a z-index, and if there are, just set the z-index of the overlay higher than the highest of the other elements.