The box model is one of the most fundamental and important principles of CSS so we will spend a decent amount of time on this and create several examples.
- Content – The text, image, input or whatever the actual content is inside the box
- Padding – The space between the content and the border on all four sides
- Border – Just what it sounds like. This is where the styling for the box ends.
- Margin – The space between the box and the other objects around it.
Every element on the page is confined to one of these boxes and the size and behavior of the box can be adjusted with these tools. Let’s make a couple of samples where we adjust the behavior of a
<div> and then a couple of
In this sample the box is the div. We select the div with our CSS and give it a background, width and margin. In this sample we have given a width of 50% (of the screen), although we can set a hard width or height with pixels also. Percentages are good because they are responsive and can help to prevent box overlap.
! Also note that by setting the margin on the sides to auto we have centered the element horizontally!
Here is a sample image grid using percentages to set the margins. Note that things aren’t going to align just the way we want them because the images are different heights! So the float-left css won’t overflow them to the next row until they can no longer align with the tallest image in the row.
If they were all the same height this wouldn’t happen because they would just float to the next row and it would be a perfect grid!