2015-03-31 64 views
0

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>

+0

你能不能顯示你的代碼? – 2015-03-31 17:47:54

+0

getBoundingClientRect應該返回一個整數,沒有像小數像素那樣的東西。你使用CSS轉換? – kursus 2015-03-31 17:49:26

+3

我不知道有一個「居中」div沒有小數像素參與的機會......並且由於不同的瀏覽器有不同的子像素渲染方法,我肯定會用javascript來彌補。 – pschueller 2015-03-31 17:49:55

回答

0

是的,你絕對可以使用整數!但是,除非您使用以整數度量的系統,否則您將遇到位置問題,因爲它是最小的度量單位。有這樣的單位嗎?是!它們被稱爲像素,並且是可以用正整數(即整數)表示的正方形單位。只要確保你在CSS中引用了像素,而不是百分比或列跨度的數量,並且你將完全掌握你的內容......

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

單擊該按鈕,您將看到基於更新方法的圓角尺寸。