Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem in calculating the width of a padded div

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Set box-sizing to border-box in your CSS, after which getComputedStyle().width will include the padding.

  2. Access the padding of the element separately with window.getComputedStyle(document.getElementById("A")).getPropertyValue('padding-right') and add it to the width.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading