【问题标题】:Center a div between another div and the bottom of the window using jQuery使用jQuery在另一个div和窗口底部之间居中一个div
【发布时间】:2012-03-16 12:05:50
【问题描述】:

我的网页布局如下...

|----------------------|
|     |----------|     |
|     | Logo div |     |
|     |----------|     |
|                      |
|     |----------|     |
|     |          |     |     
|     | Content  |     |
|     |          |     |
|     |----------|     |
|----------------------|

目前我正在尝试使用以下函数将我的div (Content) 居中:

 jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + 
                                            $(window).scrollTop() + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + 
                                            $(window).scrollLeft() + "px");
return this;

}

我从另一个 SO 问题中获得:Using jQuery to center a DIV on the screen

如果我的分辨率足够大,此功能可以正常工作,但在较小的屏幕上,它会导致div 我正集中“出现”并与上面包含徽标的div 共享空间。所以我想用 jQuery 实现的是将它垂直居中在徽标 div #logo 和页面的“结尾”之间,而不是浮动在徽标 div 的顶部。

我将如何使用 jQuery 来做到这一点?

【问题讨论】:

    标签: jquery css center vertical-alignment


    【解决方案1】:

    因为它是绝对定位的,所以你不能真正引用它与另一个 div 的关系。

    您需要做的是检查高度/宽度计算,如果它们超出最低要求,则将它们替换为固定值。您可以硬编码固定值或使用 JQuery 来获取徽标 div 的高度。

    类似的东西:

    var h = 100; //Height of logo div
    var top_position = (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop();
    
    if(top_position < h)
        top_position = h;
    
    this.css("top", top_position + "px");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多