You must have seen many different versions of this meme, all of them tell the same story, "Everybody hates CSS. I did too, in fact when I started my journey in web development, CSS for me stood for "Can be Soul Sucking". But it doesn't have to be if you've mastered the absolute basics of CSS and one of the most important and basic concept of CSS is "The Box Model".
The CSS box model is a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. Think of a webpage as a bog 3D box containing many other boxes inside it. Every element that you define in the HTML is a box.
Calculating width & height of the box
The box-sizing property defines how the width and height are calculated: should they include padding and borders. or not. There are two box-sizing properties:
box-sizing: content-box;
total width = leftBorder + leftPadding + specifiedWidth + rightPadding total height = topBorder + topPadding + specifiedWidth + bottomBorder + bottomPadding
box-sizing: border-box;
total width = specified width total height = specified height
This means that when box-sizing is set to border-box, the width of the box won't change with change in border or padding.
Box Types
display: block;
- They occupy 100% of the parent's width. - They are stacked vertically on top of each other. - Box model is applied as mentioned above. - Flexbox, List-item, table & Grid fall in the same category.
display: inline;
- They occupy their content's width - No line breaks. - No height & width. - Only horizontal paddings & margins. - width & height cannot be assigned.
display: inline-block;
- They occupy their content's width. - No line breaks. - Width & Height can be changed. - Box model is applied as mentioned above. <br>
In a nutshell, think of a webpage as a big 3D box containing many smaller boxes stacked on top of each other or side by side, some are in the front and some are in the back. That's why understanding the concept of Box Model in CSS is very important.
I hope this blog was of any help to you. Thank You.