CSS Box Model Explained

The box model in CSS is used to add spacing to different aspects of elements in a html document. There are four parts to the box model; the content that is displayed on the webpage, the border, padding, and the margin of the element.

The image below shows a graphical representation of the box model. The part in the center, labelled ‘content’, is where the text will be displayed that is put inside the html tag. The next layer shows the padding, this is spacing between the content and the border. Outside the border of the element is the margin, this is additional spacing between other elements in the html document. Using the padding or the margin depends on where you want the spacing to be, inside or outside the border. You can also use both the padding and margin in one element, they can be used in conjunction or independently.

A picture showing the css box model. The inner most square shows the content, then a square showing the padding, surrounding by a border, then the margin is the outer most square

To apply either padding or margin to an element in html you set the numeric css value of the ‘padding’ or ‘margin’ property respectively. The value of the padding or margin can be in pixels, percentage, em, etc. The code below shows an example of some CSS that is setting the border, the padding, and the margin. The padding and margin is applied to all four sides of the element.

You can also specify different values per sides of an element. You could have different padding, border, or margin per side of an element. Left, right, top, and bottom, are the different sides available in CSS. Below is a code snippet that shows how the sides of an element can be set by using a suffix to the property dependent on which side you want to set.

These CSS properties can be wrote in smaller lines of code too. The code snippet below shows how to set similar properties but in less lines of code. The first line shows setting attributes of an elements border, just by using the ‘border’. You can also set every side of the margin or padding property by supplying more numeric values to the ‘margin’ or ‘padding’ property. These values will be applied to the top, right, bottom, and left in that order. The below code will apply a padding and margin of 1px to the top, a padding and margin of 2px to the right, 3px to the right, and 4px the left of the element. Only supplying one numeric value to the ‘padding’ and ‘margin’ property will apply it to every side of the element.

One thought to “CSS Box Model Explained”

Leave a Reply