When working with sizing things in CSS, there are 4 different properties to account for:
At first when working with elements, these two properties often feel like they do the same job.
For many beginning developers the choice of
padding often comes down to whichever doesn't already have an existing value.
However, these two properties have VERY different effects on the element in play.
margin will give space around the element being styled,
padding adds room within an existing element.
The easiest way to see this in action is by having some backgrounds that are visible.
First let's look at an element with
And here's the same div with
When is 50% not 50% - Box Sizing
When working with columns, you will often want to use percentage widths or even
However, with the default settings in CSS, you have to be careful because percentages may not work the way you expect.
See this example:
The issue here is with something called the
This property tells the browser how to interpret the
border values when drawing the element on the screen.
box-sizing is set to a value called
content-box which means that the width and height are the size of the actual content and THEN padding and border are added around this element.
What this means is the
p tags above with
width: 50%; float: left; padding: 20px; are actually 50% + 20px + 20px wide (2x 20px because of left and right padding).
This can make creating grids with space between different columns a bit of a chore.
In contrast, there is another value for
border-box which calculates the
padding values from WITHIN the set
This means that while you may not know the exact size of things like images inside of your grid, you WILL know the full element size for layout purposes.
Here's the same grid from before with
box-sizing set to