Containers and Percentage Widths

I wanted to clear up something that is fairly basic but tripped me up a little when I started coding more responsive layouts. Whenever you apply a width value to a container its values for padding and margin get added to that value. In the following example the container element will actually be 640px — breaking its 600px wrapper:

<style>
.wrapper {
margin: 0 auto;
width: 600px;
}
.container {
width: 100%;
margin: 10px;
padding: 10px;
}
</style>

<div class="wrapper">
<div class="container">
<p>Lorem ipsum dolor sit amet, vix blandit epicurei verterem ad. Id sit mazim habemus platonem, at putant erroribus per, wisi autem rationibus eum cu. Ea est prodesset scripserit, in eos dicunt mentitum maluisset, pri ut timeam accusamus. Sed nominavi concludaturque an.</p>
</div>
</div>

In order to keep the container at 600px you can do some math and set its width to 560px which will allow for the added padding and margin — however — doing that with percentages will give you some unpredictable results based on the browser size.

The correct way to do this is to have two containers — one with a percentage width and one with fixed values for padding and margin:

<style>
.wrapper {
margin: 0 auto;
width: 600px;
}
.parent-container {
width: 100%;
}
.child-container {
margin: 10px;
padding: 10px;
}
</style>

<div class="wrapper">
<div class="parent-container">
<div class="child-container">
<p>Lorem ipsum dolor sit amet, vix blandit epicurei verterem ad. Id sit mazim habemus platonem, at putant erroribus per, wisi autem rationibus eum cu. Ea est prodesset scripserit, in eos dicunt mentitum maluisset, pri ut timeam accusamus. Sed nominavi concludaturque an.</p>
</div>
</div>
</div>

And remember that top and bottom margins collapse whereas left and right margins do not.