I have <div>vertically centered with the following CSS:
.v-centered {
position: relative;
top: 50%;
transform: translateY(-50%);
}
This is wonderful until its height, which was not known in advance, does not lead to the fact that its translation pushes it away from the top of the screen if the screen is too small.
I have javascript (with jQuery) to reduce 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 a scale of window resizing, it updates rather slowly. I would like a pure CSS / HTML approach or, if it is not, a function window.onresizethat does not do so many calculations.
jsFiddle
source
share