Prevent CSS Padding Changing an Elements Dimensions

July 8th, 2011 - Posted by Steve Marks to (X)HTML / CSS, Web Development.

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

This creates the following:

Without Padding

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

Now look what we get:

With Padding

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.

The Solution

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

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
Tags: , ,
This entry was posted on Friday, July 8th, 2011 at 7:11 pm by +Steve Marks and is filed under (X)HTML / CSS, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (1)
  1. This is very cumbersome. I a percent width, margins and paddings such as in responsive modern sites, with lots of child elements, it’s very difficult to figure out which padding or border doesn’t fit. CSS should allow authors to decide if a padding or a border should be considered part of the width or not. This was even planned. I don’t know if CSS3 already provide this feature.