How To calculate exact width of an element from CSS

When you specify the width and height properties of an element with CSS, you are just setting the width and height of the content area. In actual case that element is always affected by padding, border and margin.

Example: Let's say I have set css for a div as given below:


border:5px solid gray;

Now,from width property, it is clear that div consumes 250 pixels. But are we looking at css in a correct way???
Observe other properties. Padding, border and margin all are consuming few pixels. So what is the full width of a div?


Total element width = width + left padding + right padding + left border + right border + left margin + right margin

Let's calculate it in our case:

Total element width = 250 + 10 + 10 + 5 + 5 + 10 + 10 = 300

So in actual case, div will consume 300 pixels and not 250!!!

Many of us face issues while designing user interface. One of the reason is many times we miss the fact, that we have learned just now.

Note: You can use below formula to calculate exact height of an element:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin


Post a Comment