【问题标题】:Vertical centering a div with percentage based images使用基于百分比的图像垂直居中 div
【发布时间】:2012-12-23 11:48:36
【问题描述】:

我目前正在编写我的新网络作品集。到目前为止,一切都很好。我决定让它完全基于 %,我正在努力解决最后一个细节:

我必须在同样基于 % 的 div 框中垂直居中基于 % 的图像。

这里是小提琴:http://jsfiddle.net/PX4tF/4/

这不是我想要的代码:

$(document).ready(function(){

         $(window).resize(function(){

          $('.vertical_center').css({
           position:'relative',
           left: ($(window).width() 
             - $('.vertical_center').outerWidth())/2,
           top: ($(window).height() 
             - $('.vertical_center').outerHeight())/2
          });

         });

         // To initially run the function:
         $(window).resize();

        });

我当前使用的脚本只有在我调整窗口大小时才会开始正常工作。在此之前,它会使图像居中但不正确。此外,我有多个 div 框,例如页面上的那个,目前我必须复制脚本以在浏览器调整大小后正确居中。有没有办法让这更容易?

这是测试版网站的链接:http://www.zeiteffekt.de/relaunch

我不是那种编程人,所以我希望你们能帮助我。

干杯, 蒂姆

【问题讨论】:

    标签: jquery css html percentage centering


    【解决方案1】:

    试试这样

    function alignImage()
    {
        $('.vertical_center').css({
            position:'relative',
            left: ($(window).width() - $('.vertical_center').outerWidth())/2,
            top: ($(window).height() - $('.vertical_center').outerHeight())/2
        });
    }
    $(window).load(function() {
        alignImage();
    });
    $(window).resize(function() {
        alignImage();
    });
    

    调用 $(document).ready 时,图像尚未准备好。改用负载

    【讨论】:

      【解决方案2】:

      试试这个:

       $(window).resize(function(){
              $( ".img-swap").each(function() {
                  $(this).css({
                     position:'relative',
                     marginTop: ($(this).parent().outerHeight() 
                      - ($(this).outerHeight()+15))/2
                   });
               });
      });
      

      jsfiddle
      我替换了marginTop 而不是top 因为marginTop 将有助于将文本推送到图片下方,而top 仅推送图片。

      【讨论】:

      • 在像@TommySorensen 示例中那样调整窗口大小之前,这是否也有效?如果是,那就完美了。
      猜你喜欢
      • 2013-10-14
      • 2013-11-29
      • 2015-09-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2012-07-30
      • 2013-08-04
      • 1970-01-01
      相关资源
      最近更新 更多