Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one create an overlay in css?

Tags:

html

css

I'd like to create a div with an arbitrary size, then display something on top of that div. What is the best way to position and size the overlay exactly as the div below in css?

like image 736
Pieter Bos Avatar asked Mar 15 '12 16:03

Pieter Bos


People also ask

How do you overlay images in CSS?

In short, CSS overlay effects are achieved by using the following: background-image and background CSS properties to add image and linear-gradient overlay effect. position:absolute , top , bottom , right , left CSS properties to control the position of overlay image or text.

How do you make a div Overlay in CSS?

By using a div with style z-index:1; and position: absolute; you can overlay your div on any other div . z-index determines the order in which divs 'stack'. A div with a higher z-index will appear in front of a div with a lower z-index . Note that this property only works with positioned elements.


2 Answers

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.

like image 73
Andres Ilich Avatar answered Sep 23 '22 22:09

Andres Ilich


I'm late to the party, but if you want to do this to an arbitrary element using only CSS, without messing around with positioning, overlay divs etc., you can use an inset box shadow:

box-shadow: inset 0px 0px 0 2000px rgba(0,0,0,0.5); 

This will work on any element smaller than 4000 pixels long or wide.

example: http://jsfiddle.net/jTwPc/

like image 41
user1002973 Avatar answered Sep 23 '22 22:09

user1002973