Very basic question but I cannot find an answer.
Please check this fiddle.
Why does getComputedStyle fail to correctly calculate the width of the padded div? Isn’t it supposed to include all paddings & margins in the computation?
Thanks in advance!
<!DOCTYPE html>
<html lang="en">
<style>
#A {
display:inline-block;
background:red;
padding-right:100px;
}
</style>
<body>
<div id="A">a</div>
<div id="RESULT"></div>
<script>
document.getElementById("RESULT").innerHTML = "the width of A is:" + window.getComputedStyle(document.getElementById("A")).width;
</script>
</body>
</html>
>Solution :
The width does not include the padding if your box-sizing is set to content-box, which is the default. Therefore, it is not included in getComputedStyle().width. So you have two options:
-
Set
box-sizingtoborder-boxin your CSS, after whichgetComputedStyle().widthwill include the padding. -
Access the padding of the element separately with
window.getComputedStyle(document.getElementById("A")).getPropertyValue('padding-right')and add it to the width.