【问题标题】:Center child a element within different-width same-class parents在不同宽度的同级父元素中居中子元素
【发布时间】:2016-05-04 05:11:15
【问题描述】:

我即将以更具体的方式进入 jQuery 世界,因此我编写了一个函数,通过根据子元素和父元素的 outerWidth 设置 css left 属性,在相对定位的 div 中将绝对定位的锚元素居中。

这里是:

$.fn.moreCenter = function() {

    var sblockWidth = $(this).outerWidth();
    var moreWidth = $(this).children('a').outerWidth();
    var moreLeft = (sblockWidth - moreWidth)/2;

    $(this).children('a').css('left', moreLeft + 'px');

};

然后我按他们的类定位父 div:

$(document).ready(function() {
    $('.single-block').moreCenter();
});

关键是 .single-block 结构在页面的许多部分重复,每个 .single-block 可能有不同的宽度。这就是函数使用 (this) 泛化父 div 的原因。

但是,该函数似乎对每个“.single-block a”元素应用了相同的左值,该值是根据它找到的第一个 .single-block 计算得出的,而无需为每个元素重新计算。

代码有什么问题?

【问题讨论】:

标签: jquery html css centering


【解决方案1】:

SonnyPrince 转换/翻译无法在旧版浏览器中使用。

感谢 Paulie_D,我能够以这种方式通过 css 将子锚元素居中。

parent { position: relative;
         width: can be expressed in %; 
         whateverprop: whoteverset; }

child { position: absolute; 
        left: 0; 
        right: 0; 
        margin: 0 auto; }

无论如何,我什至设法通过使用 .each() 更正了上面的 jQuery 函数。

    $.fn.moreCenter = function() {
       $(this).each(function() {
         var sblockWidth = $(this).outerWidth();
         var moreWidth = $(this).children('a').outerWidth();
         var moreLeft = (sblockWidth - moreWidth)/2;

         $(this).children('a').css('left', moreLeft + 'px');
       });
    };

问题解决了,谢谢大家:)

【讨论】:

    【解决方案2】:

    仅使用 CSS 的一个非常简单的解决方案是:

    .single-block {
        left: 50%;
        position: absolute;
        transform: translateX(-50%);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      相关资源
      最近更新 更多