How can I fix top and bottom of content getting cut off when vertically centering using jquery?

StackOverflow https://stackoverflow.com/questions/21916828

  •  14-10-2022
  •  | 
  •  

Question

I have a simple landing page I am making and I am using jquery to vertically center the content on the screen. I chose jquery since the height of the container is undefined.

The script works fine except when the screen is very narrow in width (like a mobile phone), the top and bottom get cut off and there is no way to scroll to the top and bottom. I have created a fiddle to show the issue I am having. If you make the width very narrow, you can see that content gets lost.

Is there a simple solution for this?

Thanks

Fiddle

    $(window).resize(adjustLayout);
/* call function in ready handler*/
$(document).ready(function(){
adjustLayout();
/* your other page load code here*/
})

function adjustLayout(){
$('.main').css({
    position:'absolute',
    left: ($(window).width() - $('.main').outerWidth())/2,
    top: ($(window).height() - $('.main').outerHeight())/2
});

}
Was it helpful?

Solution

Check for negative values..

function adjustLayout(){
        var subheight=($(window).height() - $('.main').outerHeight())/2;
        $('.main').css({
            position:'absolute',
            left: ($(window).width() - $('.main').outerWidth())/2,
            top: (subheight>=0)?subheight:0,
            bottom: (subheight>=0)?subheight:0,
        });

    }

And handle overflow:

 <div class="main" style="margin: 10px; padding: 10px; max-width: 800px; text-align: center;overflow:auto;">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top