Can you explain the box model again? How do I determine the correct width of an element when I have a margin and/or padding?

All HTML elements can be thought of as boxes. The “box model” is essentially a box that wraps around elements and it consists of margins, borders, padding and the actual content. It also allows you to add a border around the elements and to define space between them.

Here is a great article on the box-model that will help explain how all of the different parts of the box model affect the total size of an element:

See it in action in the developer tools! Under the Elements panel Computed pane you can examine and edit the element's "box":

The concentric rectangles give you information about the padding, border, margin, width and height of an element. You can even click on the values to edit them!

Then it is just a matter of some quick math to determine an element's total width and height.

One thing to note is, if you set a fixed width or height on an element, the site assumes you want that interior box to always remain that width and height, so it will add any padding and margin to the total width or height of that box. For example, if I have a box that is naturally 500px wide (that was simply the space left on the screen; I didn't set the width), if I added 25px of padding to all sides, the interior width would become 450px and the box would remain 500px wide. BUT if I gave the box a fixed width of 500px and added 25px of padding to all sides, the interior width remain 500px and the 25px would be added to the total width--making the box 550px wide, ultimately. 

Browsers, or your CSS boilerplate, may apply default styles to certain elements like paragraphs or headers, which you may want to override or account for in your stylesheet. Looking at an element with the developer tools can help identify those default styles.

Still need help? Contact Us Contact Us