Today I want to share with you a scenario I find myself coming across on a day-to-day basis and one that had me stumped when I first started to build HTML websites; the fact that when you add padding to a HTML element it has a direct impact on the width and height of that object.
Let’s take a look at an example of this in action. Below I have included a simple HTML div with a fixed width of 300 pixels:
<div style="width:300px; background-color:#CCC"> This div is 300px </div>
This creates the following:
Now lets add 50 pixels of padding to the left side of the div:
<div style="width:300px; padding-left:50px; background-color:#CCC"> This div is 350px </div>
Now look what we get:
Seem a bit odd? Allow me to explain…
It’s all down to the CSS Box Model. In a nutshell the width value that we set on the div is the amount of space that can contain content. The 50 pixel padding that we added in the above example cannot contain any content (ie. will be blank space) and is therefore added to the 300 pixel width. This is the same for borders in that if we were to add a border to the div this would be added to the width also.
There are two solutions I normally use to combat the explained scenario:
Subtract the padding from the dimensions
Using the example from above one option would be to subtract the padding value from the width. Our width was 300 pixels and the padding was 50 pixels so our new width would be 250 pixels:
<div style="width:250px; padding-left:50px; background-color:#CCC"> This div is 300px </div>
Add the padding to a child element
My preferred option is to keep the 300 pixels on the main div but add another div inside that contains the padding. Let me show you:
<div style="width:300px; background-color:#CCC"> <div style="padding-left:50px"> This div is 300px </div> </div>