Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 437
EnexoOnoma Avatar asked Mar 12 '15 10:03

EnexoOnoma


2 Answers

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

like image 150
ChaosClown Avatar answered Sep 27 '22 20:09

ChaosClown


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();
like image 25
Josh Crozier Avatar answered Sep 27 '22 19:09

Josh Crozier