Vertically centered block using negative margin

Some times you want to show a pop-up in HTML (something like jquery fancy box, light box, flowplayer overlays). The trick to make an overlay is to add a div at the end of the body DOM tree, this semi-transparent block would cover the entire screen to prevent interaction with content beneath it, this can be done by having a semi-transparent png image as background or a using RGBA background (background-color:rgba(255,255,255,0.75);) or using a opacity ...etc. Usually div is created in JS when the library is initialized.

Let's assume we want to show a box at the top, this is very easy by having top:0

To make it at the bottom we can't set top:100% because then it's top corner will be place at the bottom of the screen, but we can set bottom:100% ie. place the bottom corner of the box at the bottom which is what we want.

If we have a box 200px in height, and we want to center it vertically we can not simply say top:50% nor bottom:50% and there is no such thing as middle:50%, so ?

The problem with top:50% is that the box is shifted by 100px downward, we can fix that using negative margin 100px upward, margin:-100px auto 0;

margin:-100px auto 0;

If you want to show a single-line message you may use 1em and -0.5em respectively.

It's very important to use flexible design, using percentages is one of the methods and this article shows a good trick instead of attaching an a javascript event on window resize.


Popular posts from this blog

Multi-host docker cluster using OVS/VxLAN on CentOS 7

Be aware! Docker is a trap.

CSS3-based animation instead of jQuery