I am developing a jQuery function to vertically center an element. The function is triggered on load and here is the code:
JQuery
var $window_height;
function Centerize(content) {
content.css('margin-top', (($window_height - content.height())/2))
};
$(function(){
$window_height = $(window).height();
Centerize($('#welcome'));
$(window).on('resize',function(){
$window_height = $(window).height();
Centerize($('#welcome'));
});
})
However, I encountered an issue where upon resizing the window, the height of my div changes unexpectedly (decreases by 60px). This results in the margin-top increasing, pushing the entire div downwards.
I have verified this by using console logs for $('#welcome').height().
The initial value is 432px. After resize, it drops to 361px and remains so even when maximizing the browser window. Any suggestions?
SCSS:
#welcome {
margin: 0 auto;
background-color: #DB9E36;
border-radius: 30px;
width: 800px;
padding: 30px 50px;
text-align: center;
div {
margin: 50px auto;
background-color: #FFE34E;
width: 300px;
height: 50px;
border-radius: 5px;
a {
display: inline-block;
text-decoration: none;
font-family: 'Quicksand', sans-serif;
font-weight: bold;
color: #FFFAD5;
background-color: #BD4932;
width: 100px;
margin: 10px 10px;
padding: 5px 0;
}
}
}