Making Layout Easy With Box-sizing

The default CSS box model can be tricky to deal with. The 'width' of a box does not include the padding or borders. Those are actually added on to the declared width to make up the final width of what you see in the page. So if you want a box to span half the page and you simply give it a width of 50% and then a padding of 20px, you end up with something wider than half the width of your page. Now you could do some math to figure out what percentage width you need to declare to make your box and padding span half the width of the page ... or you could use the box-sizing property.

Here is an example. Let's say you create two divs, each of which should occupy half the width of the page, like this:

1
2
3
4
5
6
7
8
<div class="page">
 
<div class="box">My Box</div>
<div class="box">My Second Box</div>
 
<div style="clear:both;"></div>
 
</div>

Then you add some styles to float the two boxes next to each other:

1
2
3
4
5
6
7
8
9
10
11
12
<style>
.page {
width:100%;
border:3px solid #999;
}
.box {
width:50%;
border:3px solid #f99;
padding:20px;
float:left;
}
</style>

The result will look like this:Screen Shot 2014-01-20 at 7.03.14 PM
The boxes are too wide and do not fit next to each other on the page.

Let's try to adjust the width by changing the percentage value.

1
2
3
4
5
6
7
8
9
10
11
12
<style> 
.page {
width:100%;
border:3px solid #999;
}
.box {
width:40.45%;
border:3px solid #f99;
padding:20px;
float:left;
}
</style>

The boxes now fit next to each other.Screen Shot 2014-01-20 at 7.03.54 PM
but as soon as we resize the page, everything shifts again. So this is clearly not a good soluton.Screen Shot 2014-01-20 at 7.05.07 PM

Now let's take advantage of the box-sizing property:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
.page {
width:100%;
border:3px solid #999;
}
.box {
box-sizing:border-box;
   -moz-box-sizing:border-box; /* Firefox */
   -webkit-box-sizing:border-box; /* Safari */
width:50%;
border:3px solid #f99;
padding:20px;
float:left;
}
</style>

Now the boxes are actually half the width of the page and now matter how much you resize the page, they stay in place.

Screen Shot 2014-01-20 at 7.05.59 PM

Screen Shot 2014-01-20 at 7.06.38 PM

Leave a Reply

Your email address will not be published. Required fields are marked *

Message
Your Name *
Your Email *
Website

Contact us

Contact us about LoudFeed services

Get in touch with us

Name: Loud Feed Services Administrator
Address: Brooklyn, NY
×
20126155