Simplifying CSS Box Model with Box-Sizing

by | September 19, 2022 | CSS, Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

Last updated on: February 8, 2023

The CSS “box model” is confusing. Mainly because an element’s width is the width of the element plus its padding-width and border-width. Setting your element’s width to 100% and assigning 20px padding actually results in a width of 100% + 40px. That’s not only confusing, but it’s difficult to work with. Instead, you can simplify the CSS box model using the box-sizing property.

Here’s an idea of how CSS box model works. The “width” of this element is 794px, but the actual width is 794px + 5px + 20px + 20px + 5px (totaling 844px) which results in you doing math and a convoluted way of keeping track of numbers while you’re developing your website’s styling.

CSS Box Sizing Content Box

Changing box-sizing from content-box to border-box makes everything simpler and easier to work with.

Here’s an example to implement box-sizing border-box using Sass:

html {
  box-sizing: border-box;
}

* {
  &,
  &:before,
  &:after {
    box-sizing: inherit;
  }
}

See how easy that is?

Get every element on the page using box-sizing border-box with just a few lines of CSS (or Sass, as used in the example).

This way, when you apply border-width and padding to an element the additional width is included in the element’s width — so, width: 100%; is truly 100% of the available width and your border and padding widths are accounted for inside of that space instead of as additional pixels.

For further discussion, check out the comments on this post from CSS-Tricks dating back to 2014.

Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

2 × two =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest