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
you should stick to a CSS solution though, there are several way to achive this
.alignVertical {
position:relative;
display:inline-block;
top:50%;
transform:translateY(-50%);
}
jsfiddle: https://jsfiddle.net/jorjmt70/
or using flexbox
.parent {
display:flex;
height:100vh;
background-color:red;
justify-content:center;
align-items:center;
flex-direction:column;
}
jsfiddle: https://jsfiddle.net/mdh9h876/
if you want to use flex box use autoprefixer to get deeper browsersupport: https://github.com/postcss/autoprefixer
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With