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

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

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




Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}