Jamie Johnson, December 5, 2019
Look at the picture above with the text vertically centered on top of it. Guess what? It works at different resolutions. We all know the pain of vertically centering an element over another one when mobile resolutions are a consideration (and they should be). In the desktop-resolution-only days, one just needed a table cell with valign equalling center. Then later one could use CSS for display: table-cell and vertical-align: center. However, that doesn't account for the "background" image. People have come up with all sorts of tricks to accomplish this and others have just manually made their best shot.
I'd like to offer my solution. It dynamically centers an element vertically over an image while allowing that image to be fluid with the resolution for adaptive/responsive behavior while maintaining the vertical centering of the element. Resize this screen to see how it works above, but make sure to pause after a resize so it can respond.
A couple things to keep in mind:
<body onresize="location.href=window.location">
<style><!--
/* custom css */
#vctrcontainer #centeredElement {
color: #f1f1f1;
font-family: arial;
font-style: italic;
}
--></style>
<div id="vctrcontainer">
<div id="centeredElement"><h1>Dynamic, Vertical Center over an Image</h1></div>
<img src="space-war-facebook-cover-4218.jpg" onload="vctr(this,document.getElementById('centeredElement'),36);" />
</div>
Take note of the 36 in the call to the vctr function. It is called when the image is loaded so that it won't "measure" the image before the image loads. It takes 3 parameters: The element the image fills, the element with the text and a number, in this case 36. So why the 36? That is the height of the element(s) above the image. So, if you have 60px tall menu bar at the top of the screen, then you would use 60 instead of 36. In this case, I used 36 since the paragraph at the top is of height 18px (and line-height and font-size are both 18px) and has padding of 9px. This means 9 at top, then 18 and another 9. So 9 + 18 + 9 = 36. I have 36 pixels at the top and this is retained while the image is resized and the text is overlayed with vertical alignment centered.
So there you go if you want to use it!