Thinking Inside The Box ‒ CSS Box Model
Grab your copy of CSS Visual Dictionary incl. diagrams of all CSS properties.
To get a good idea of how flex works try flex layout editor on this page.
It’s tempting to start tweaking HTML element’s CSS properties before getting a good grasp on the CSS box model. Besides, you have already seen it in Chrome developer’s console. It looks something like this:
The box in the CSS box model is the content area.
By default padding, border and margin are set to 0px. This makes the HTML element with default CSS box-sizing style of content-box, a 1px border and dimensions of 300 x 100 look like this:
Things start to get interesting when padding is added ‒ in this case 16px.
The padding thickness now surrounds the element. Notice that the element’s physical dimensions are now 332 x 132 and not the originally set 300 x 100 because 32 (16 + 16) padding was added to each side.
This isn’t always a problem at all ‒ in fact outer padding is what you will see implemented on most web sites ‒ because assuming default values is generally a good thing.
However, sometimes this makes it difficult to predict the final dimensions of the element. Wouldn’t it be better if we could contain padding within the defined dimensions of the element instead? That’s another possibility!
It is achieved by overriding box-sizing with a value of padding-box.
The padding was “inverted” and now you’re thinking inside the box! This way the original dimensions of 300 x 100 are preserved.
Now that padding is on the inside of our box area it is effectively shifting content closer toward the middle by 16 pixels on each side.
It’s a nice model for creating pixel-perfect User Interface elements!
But remember that there is also border. Fortunately for us, we can push the border inside of an element in the same way by using border-box value.
But first, let’s take a look at an element with default padding and border:
Using border-box it is possible to push border and padding inside the box:
Now both padding and border are on the inside, too. But what about margin? It would be good if we could use “margin-box” and stuff all 3 parameters inside the content area.
But by definition margin is an area outside of content.
So even though in your deepest hacker desires you may want to wish for one… it wouldn’t make much sense to implement it and keep good conscience.
There is no margin-box. Sorry but not sorry. The reason is obvious.
More stuff like this in my book.
Limited Time Offer
The diagrams in this tutorial were influenced directly by the manuscript!
Medium Readers Only:
== grab a copy ==
Contains all CSS properties.