當元素包含內嵌填充塊的內嵌塊時,它不包含在元素的寬度計算中。jQuery寬度不包含內部元素填充
基本上與jQuery outerWidth on a parent element which has child elements with padding相同的問題。
此頁面應該沿着綠色框的右側排列文字 但是文本將始終比它的容器變大,因爲寬度永遠不會包含它的任何子項的填充。
有沒有辦法正確找到元素的寬度,而無需手動枚舉所有子元素並重新添加每個子元素的填充?使用.css('width')
,.width()
或.outerWidth()
時結果相同。
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
jQuery(document).ready(function() {
var e = jQuery('#BLAH');
var pw = e.parent().width();
e.css('font-size','1px');
if (e.outerWidth() < pw) {
while (e.outerWidth() < pw) {
alert('width ' + e.outerWidth() + ' < ' + pw);
e.css('font-size','+=1px');
}
e.css('font-size','-=1px');
}
});
</script>
<style>
#BLAH {
background-color: red;
white-space: nowrap;
}
.BLAH {
//padding: 0 10%;
background-color: blue;
display: inline;
}
</style>
</head>
<body>
<div style="background-color: green; width: 50%; height: 50%">
<div id="BLAH" style="display: inline-block;">
<div class="BLAH">BLAH</div>
<div class="BLAH">BLAH</div>
<div class="BLAH">BLAH</div>
<div class="BLAH">BLAH</div>
</div>
</div>
</body>
</html>
看看['box-sizing:border-box'](http://www.paulirish.com/2012/box-sizing-border-box-ftw/) – kei
該問題似乎特定於基於百分比填充。我認爲問題是如果考慮百分比填充,則嘗試和計算寬度將是一個無限循環。填充影響寬度,但寬度影響填充。 –
不是一個無限循環:parentWidth = totalChildFixedWidths /(1-totalChildPercentPadding),但是W3C決定宣佈常識實際上是未定義的行爲,而不是做明顯的事情...... – user3338098