简体   繁体   English

使用jquery垂直居中时,如何解决内容顶部和底部被截断的问题?

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

I have a simple landing page I am making and I am using jquery to vertically center the content on the screen. 我正在制作一个简单的登录页面,并且正在使用jquery在屏幕上垂直居中放置内容。 I chose jquery since the height of the container is undefined. 我选择jquery是因为容器的高度是不确定的。

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
});

}

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;">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM