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:
I did not keep the top of the template for this page as it changes size and I didn't want to factor that into the calculation (though it could be if I made this more complicated).
That said, this is for a feature image or splash image or lead image at the top of a web page, such as for an article.
It's not perfect, but it is an option for your toolbox.
I will list the code elements in the order that I used them (or you cna just view the source).
Ensure you have your body tag look like this so that the page can re-calculate the layout of the centered element:
Ensure you use something like the following HTML markup where you have the content at the top of the screen:
<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);" />
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.