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?
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With