How can one create an overlay in css?

You can use position:absolute to position an overlay inside of your div and then stretch it in all directions like so:

CSS updated *

.overlay {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color:rgba(0, 0, 0, 0.85);
    background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAATSURBVBhXY2RgYNgHxGAAYuwDAA78AjwwRoQYAAAAAElFTkSuQmCC) repeat scroll transparent\9; /* ie fallback png background image */
    z-index:9999;
    color:white;
}

You just need to make sure that your parent div has the position:relative property added to it and a lower z-index.


Made a demo that should work in all browsers, including IE7+, for a commenter below.

Demo

Removed the opacity property from the css and instead used an rGBA color to give the background, and only the background, an opacity level. This way the content that the overlay carries will not be affected. Since IE does not support rGBA i used an IE hack instead to give it an base64 encoded PNG background image that fills the overlay div instead, this way we can evade IEs opacity issue where it applies the opacity to the children elements as well.

Leave a Comment