水平中心元素没有分数偏移?

时间:2015-03-31 16:57:43

标签: css html5 css3

margin: 0 auto将水平居中一个元素。但是,根据父级和子级大小,有时getBoundingClientRect会返回小数左侧值(jQuery偏移量也是如此)。这些分数会导致javascript代码中的其他问题,所以我想删除它们(而不是补偿它们)。

有没有办法使用css以整数偏移量水平居中?或者我应该只使用javascript?


有许多水平对齐问题,但似乎都没有解决亚像素困惑问题。



var br = document.getElementById("kid").getBoundingClientRect();

document.getElementById("info").innerHTML = "left: " + br.left;

body {
  margin: 0;
}
#pop {
  position: absolute;
  width: 401px;
  height: 100%;
  background-color: pink;
}
#kid {
  width: 100px;
  height: 100px;
  background-color: orange;
  margin: 0 auto;
}

<div id="pop">
  <div id="kid"></div>
  <div id="info">d</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以重新定义Element.prototype.getBoundingClientRect,以便返回舍入的数字。

这也会影响依赖它的jQuery方法,例如offset()width()height()

Element.prototype.getBoundingClientRect= function() {
  var parent= this.parentNode instanceof HTMLElement ? this.parentNode : null,
      left  = Math.round(this.offsetLeft + (parent && parent.getBoundingClientRect().left)),
      top   = Math.round(this.offsetTop  + (parent && parent.getBoundingClientRect().top)),
      width = Math.round(this.offsetWidth),
      height= Math.round(this.offsetHeight);

  return {
    left:    left,
    top:     top,
    right:   left+width,
    bottom:  top+height,
    width:   width,
    height:  height
  }
} //getBoundingClientRect

this Fiddle中,您将使用JavaScript和jQuery查看元素的小数维。然后重新定义getBoundingClientRect

单击按钮,您将看到基于更新方法的圆角尺寸。

答案 1 :(得分:0)

是的,你绝对可以使用整数!但是,除非使用以整数测量的系统作为最小测量单位,否则您将遇到位置问题。有这样的单位吗?是!它们被称为像素,并且是可以用正整数(即整数)表示的正方形单位。只需确保您在CSS中引用像素而不是百分比或列间距数量,您就会得到您正在追求的内容......

相关问题