I have a <div>
that's vertically centered with the following CSS:
.v-centered {
position: relative;
top: 50%;
transform: translateY(-50%);
}
That's great as long as its height, which is not known beforehand, does not cause its translation to push it off the top off the screen in the case that the screen is too small.
I have some javascript (with jQuery) to mitigate this:
var $myDiv = $('#myDiv'),
paddingTop = parseInt($('html').css('padding-top'));
window.onresize = () => {
if ($myDiv.is('.v-centered')) {
if ($myDiv.position().top < paddingTop) {
$myDiv.removeClass('v-centered');
}
} else {
if ($myDiv.height() < document.body.offsetHeight) {
$myDiv.addClass('v-centered');
}
}
}
However, this is a bit ugly and, on the scale of resizing-a-window updating, is pretty slow. I'd love a pure CSS/HTML approach, or failing that, a window.onresize
function that doesn't do so much calculation.