The CSS Box Model Explained Once and For All

Every element in CSS is a box, and misunderstanding how that box’s dimensions are actually calculated is responsible for more layout confusion than almost anything else in CSS.

/* Default (content-box): width applies only to content,
   padding and border are ADDED on top */
.box-default {
    width: 300px;
    padding: 20px;
    border: 5px solid black;
    /* actual rendered width: 300 + 40 + 10 = 350px */
}

/* border-box: width INCLUDES padding and border */
.box-border {
    box-sizing: border-box;
    width: 300px;
    padding: 20px;
    border: 5px solid black;
    /* actual rendered width: exactly 300px */
}

/* Almost every modern stylesheet starts with this reset */
*, *::before, *::after {
    box-sizing: border-box;
}

Setting box-sizing: border-box globally is close to a universal best practice at this point — it makes width calculations behave the way most developers intuitively expect, and virtually every CSS framework and reset does this by default.