HTML5 Zone is brought to you in partnership with:

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5. Paul is a DZone MVB and is not an employee of DZone and has posted 127 posts at DZone. You can read more from them at their website. View Full User Profile

Use Box Model for Easier Widths

11.12.2012
| 2150 views |
  • submit to reddit

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




Published at DZone with permission of Paul Underwood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)