Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Use Box Model for Easier Widths

DZone's Guide to

Use Box Model for Easier Widths

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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




What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}