How to keep div in center-height when I resize the browser window?

I am trying to center in height a div, however it does not work when I resize the browser screen.

How to edit this to achieve the adjustable margin-top on resize?

Thank you

<script>
  var h = $(window).height();
  var parentHeight = h;
  var childHeight = $('#a-middle').height();
  $('#a-middle').css('margin-top', (parentHeight - childHeight) /2);
</script>

Edit: The answer should be in js since flexbox won’t work on IE-9


solution

Although you can easily do this with pure CSS, your bounty stated that you want a JS answer.

If you are interested in a pure CSS answer, see this answer that has multiple different methods on how to center elements vertically/horizontally.


You could simplify your jQuery to the following:

$('#a-middle').css('margin-top', function () {
  return ($(window).height() - $(this).height()) / 2
});

Then you could just place this within a resize event listener and chain the .resize() method in order to trigger the event initially when the browser loads.

Example Here

$(window).on('resize', function () {
  $('#a-middle').css('margin-top', function () {
    return ($(window).height() - $(this).height()) / 2
  });
}).resize();

JavaScript equivalent (without jQuery):

Example Here

var verticalCentering = function () {
var el = document.querySelector('#a-middle');
  el.style.marginTop = (window.innerHeight - el.offsetHeight) / 2 + 'px';
}
window.addEventListener('resize', verticalCentering);
verticalCentering();