DEV Community

Cover image for CSS Box Model
Megan Grusenmeyer
Megan Grusenmeyer

Posted on • Edited on

CSS Box Model

When you're learning CSS it can be hard to distinguish between margins, borders and padding. When should you use negative numbers? How do these elements interact? This blog covers the box model, or how these elements work together to create the layout on the page.

HTML elements are organized into boxes. Text, images, and other features are can be sized, but what if you want to control how close elements are to one another? That's where padding, borders and margins come in. Together they make up the box model.

Let's inspect these pieces starting with the innermost layer and working our way out.

Padding

Padding is the space between the content and the border. It's often whitespace. It starts at the content edge. Some examples of padding include the whitespace between the text and the border in an advertisement in a newspaper that's outlined. Buttons typically have padding between their text and the edge of the button.

Padding provides visual rest for the eye and keeps things from getting overcrowded.

With CSS you can specify padding for the entire box or for specific sides.

Image description

Borders

Moving outward from the padding, the next layer is the border. There are plenty of border properties that allow you to create exactly the trim you need to set an element out from the rest of the page.

Width - thickness of the border itself
Style - solid, dotted, dashed, double, ridge, inset, outset..
Color - includes transparency
Position - specify side(s) that will have a border
Radius - curve the edges or your border to a custom radius. You can specify which corners

Here one element, heron has three properties. You can combine these using only ‘border’ as seen with hibiscus

Image description

Margins

Margins are the space around your borders. Like padding, they create whitespace and visual rest. Specifying a margin ensures other elements won't crowd this one.

Image description

A final note

on the box model: CSS' width property applies to the box itself. Margins, borders and padding are all extra.

If your width is 400px and you have 10px padding, a 2 px border and a 30 px margin, the whole element is 484px (assuming you have the same size padding, boarder and margin on all sides).

Top comments (0)