When we are thinking about the content on the website, we think about the text, images, videos, forms on the page. Depending on what type of content we are dealing with, we can specify the width and height of our content.
If we don’t specify a width and height, then in case of block elements the content itself will take up 100% of the width of its parent container. The height is then determined by how much content there is.
We can specify a width for our content. But when we start using padding, border, and margin the width and height will also start changing.
By default all HTML elements are contained in some kind of box. It can be a simple div.
The base width of a box is determined either by the width of the parent element, or by explicity setting a width. The height will be determined by the amount of content.
Once we add padding our boxes will get larger. If you add a padding of 15 pixels everywhere, both the width and the height will increase by 30 pixels (15 pixels on both sides). Borders and margins work the same way, increasing the width and height.
The final width of your box = content width + padding + border + margin.
Let’s say we have one div inside another. If the parent div has a width specified and the child div doesn’t, then the child div will take up the same amount of space as its parent.
In this case if you add padding to the inner div, it will shrunk to fit the width of the parent div. If you do specify the width of the child element to be 100% of the parent and add padding at the same time, the inner div will overflow the outer div.
You have to be careful with adding padding, borders, and margins in multi-column layouts as the available space will shrink and it may collapse into one column.
Absolute Position and Floats
In case of absolutely positioned or floated elements the content won’t take up 100% of the available space, but only the space it needs to be displayed.
- line height remains the same
- left and right paddings are affected
- if you add a background color, the padding is visible, but it doesn’t push content out of the way
- doesn’t affect the spacing between the lines
- the left and right edges are affected
- there won’t be borders at line breaks
The box-sizing property
If you don’t want to do math with all your paddings etc. there is one handy CSS tag that you’ll find useful: box-sizing.
The default value of box-sizing is content-box. It means that the width you set for the box is set to the content. If you change that to border-box the width of the box will include the padding and the border. It still doesn’t include the margin, but can simplify things a lot.
The CSS box model is simple but as all things programming, needs practice to really get a grasp of it.
Latest posts by jay (see all)
- The Difference Between Git and Github - July 20, 2019
- How to write ES6 code that’s safe to run in the browser - March 2, 2019