【问题标题】:How can I fix top and bottom of content getting cut off when vertically centering using jquery?使用jquery垂直居中时如何修复内容的顶部和底部被截断?
【发布时间】:2014-03-21 22:17:11
【问题描述】:

我正在制作一个简单的登录页面,我正在使用 jquery 将内容垂直居中放置在屏幕上。我选择了 jquery,因为容器的高度是不确定的。

脚本运行良好,除非屏幕宽度很窄(如手机),顶部和底部被截断,无法滚动到顶部和底部。我创建了一个小提琴来显示我遇到的问题。如果你把宽度做得很窄,你会看到内容丢失了。

有没有简单的解决方案?

谢谢

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

}

【问题讨论】:

  • 您是否尝试过任何仅使用 css 的方式来使内容居中?有多种方法,如果需要在移动设备上使用媒体查询,您可以使其表现不同。
  • 我认为您可以在不使用任何 javascript/jQuery 的情况下垂直居中内容的更好选择。以下是您可以使用的 6 种方法:6 Methods For Vertical Centering With CSS

标签: jquery vertical-alignment


【解决方案1】:

检查负值..

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

    }

并处理溢出:

 <div class="main" style="margin: 10px; padding: 10px; max-width: 800px; text-align: center;overflow:auto;">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2020-04-25
    • 2017-10-28
    • 1970-01-01
    • 2010-10-01
    • 2015-04-01
    相关资源
    最近更新 更多