0

Use Box Model For Easier Widths

Here is a quick tip on working with width’s in CSS. There are multiple things that make up the width’s of the HTML elements, the width, the padding and any borders on the element.

Total Width = Width + Padding + Border.

This means that if the width of the element is 500px with a padding of 50px and a border of 10px the total width of the element is 620px.

620px = 500px + (50px x 2) + (10px x 2).

This makes it a bit more difficult when working out complicated layouts, or if you want to increase the padding or borders at a later date you have to change the widths of existing elements.

There is a CSS property call box-sizing which makes this work a lot easier. Using the box-sizing property with the value border-box will include the padding and the border in the width of the element. This changes the maths we do to work out the actual width of the element.

div {
box-sizing: border-box;
}

The actual width of the element will now be the width of the element including padding and border.

Total Width = (Width – Padding – Border) + Padding + Border

If we use the same example as above, if the width of the element is 500px with a padding of 50px and a border of 10px the total width of the element is 500px.

500px = 380px + (50px x 2) + (10px x 2)

Apply To All Elements

If you prefer this way of working and want to always work this way then you can apply this property to all elements by using the following.

* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}

You may think that using a * selector is slow but Paul Irish has developed some tests to see the difference in speed. This is evidence that is only adds a 4% change in the speed of the CSS rendering.

Box-Sizing Tests

Browser Support

The box-sizing property is supported on all major browsers so you don’t need to worry about using this property right now.

Internet explorer has supported this property since IE8.

Firefox has supported box-sizing since version 2, but it will only support the -moz- prefix property.

Chrome used to only support the -webkit- prefix version until version 9 and now it will support the unprefixed version.

To keep updated with browser support of the box-sizing property you can view it here http://caniuse.com/css3-boxsizing.

This article was originally published on Use Box Model For Easier Widths.


 

Leave a reply