To vertically centering a div that overlays over another div, a simple solution is to set style of the top layer to top: 0; left:0; bottom:0; right:0;
. However, it doesn’t seem work well if the background layer is scrollable. Here is another solution for vertically centering an overlay div is to use top: calc(50%-0.5*div.height)
, where the div.height is the height of the foreground div which can be calculated dynamically using javascript. The following is the complete example.
For more information getting height of div, you may read the post How to get height of a div element with JavaScript/jQuery.
You can check out the effect of the above example in CodePen Overlay.