CSS Margin Summary

Margin is space outside an element. It pushes the element away from other elements around it.

.box {
	margin: 20px;
}

Margin Creates Outside Space

Every HTML element is treated like a box. Margin is the space outside that box.

If two boxes are too close together, margin is one of the most common ways to create space between them.

.card {
	margin: 20px;
}

Margin On All Sides

When you write one margin value, the same amount of space is added to all four sides of the element.

.box {
	margin: 20px;
}

This adds 20 pixels of space outside the top, right, bottom, and left sides of the box.

Margin On One Side

You can also add margin to only one side. This is useful when you only need space in one direction.

.box {
	margin-bottom: 20px;
}

Margin-bottom is used very often because text, cards, images, and sections usually need space below them.

The Four Margin Properties

CSS gives you a separate margin property for each side of the box.

.box {
	margin-top: 10px;
	margin-right: 20px;
	margin-bottom: 30px;
	margin-left: 40px;
}

This lets you control the space around an element very directly.

Margin Shorthand

Margin can also be written in a shorter form. This is called shorthand.

.box {
	margin: 10px 20px 30px 40px;
}

The values go in this order: top, right, bottom, left.

You do not need to use shorthand right away. It is usually easier to start with margin-top, margin-right, margin-bottom, and margin-left until the pattern feels familiar.

Margin Auto

Margin can also use the value auto. This is commonly used to center a block element that has a set width.

.box {
	width: 300px;
	margin-left: auto;
	margin-right: auto;
}

This creates automatic space on the left and right sides, which centers the box inside its parent.

Margin And Padding

Margin and padding are easy to confuse. Padding is inside the box. Margin is outside the box.

.box {
	padding: 20px;
	margin: 20px;
}

Padding creates space between the content and the edge of the box. Margin creates space between this box and other boxes.

Code Sandbox

AI Tutor