To create simple overlays without help of any help of readymade jQuery plugin or third-party library we need to use CSS to achieve that.
Steps to make overlay with CSS
- Create <div> node and make it absolute to DOM (document object model)
- Assign it property top and left = 0.
- Apply width and height 100%
- Finally set z-index > 0
So <div> will overlay entire document. Now let’s make div centered different way.
Method 1:- Making overlay div center with css top, right, bottom and left property.
HTML
<div id="overlay1">your content</div>
CSS
#overlay1 { margin: auto; position: absolute; top: 50px; left: 50px; bottom: 50px; right: 50px; background-color: #000; color: #FFF; z-index:5; }
Above method will set div position 50px from all corner and margin auto will make this div centered.
Demo –
Method 2: Making overlay div with css margins.
HTML
<div id="overlay2">your content</div>
CSS
#overlay2{ position:absolute; left:0; right:0; margin-left:auto; width:300px; margin-right:auto; background-color: #000; color: #FFF; z-index:5; }
Above method will set overlay <div> to top,left =0 position and then set it’s margin auto.
Demo:-
Method 3:- relative div inside absolute div
HTML
<div id="overlay3">your content</div>
CSS
#overlay3{ top:15%; position: absolute; left: 50%; z-index:5; } #overlay3 div{ position: relative; left: -50%; border: 1px solid #666; background-color: #000; border-radius:5px; color: #FFF; min-width:300px; z-index:6; }
In above example there are two nested <div>. The parent one is absolute to DOM while child <div> is relative to it. So, parent is made 50% left to the viewport first. Then half of the child div’s wide is taken as offset to move it right. i.e. left:-50%
Demo –
Method 4:- absolute div inside relative div
HTML
<div id=”overlay4”>your content</div>
CSS
#overlay4{ position:relative; top:0; left:0; width: 100%; z-index:5; } #overlay4 div{ position: absolute; left: 50%; margin-left:-150px; border: 1px solid #666; background-color: #000; border-radius:5px; color: #FFF; width:300px; z-index:6; }
In above example there are two nested <div>. The parent one is relative to DOM and set it to top,left = 0. Child <div> is absolute to it. It’s set to 50% left to document and then shifted right to half of its width.
Demo: –
Method 5:- lightbox overlay div
To make above code practical, let’s change absolute and relative order and add one semi transparent background.
Demo:-