Use quote marks to find an "exact phrase"

Print version

print icon

22: Margins and padding

Margins and padding

Margins and padding are handy, everyday things in web design, used in everything you'll do. They're not rocket science, but they are similar enough to cause confusion, so you should make sure you understand them up front.

The paragraph on the left below has a margin but no padding, and the one on the right has padding but no margin. Both take up the same amount of space. Each paragraph has a yellow background to show its size.


This paragraph has a margin on all sides


This paragraph has padding on all sides

An element can have both padding and a margin.

Specifying margins and padding

You can set the margins and padding for each side individually. You can use either the longhand format, shown on the left below, or the shorthand version on the right (they're identical in meaning). Note the order in the shorthand version: top / right / bottom / left. Several CSS properties have a shorthand version available. Get in the habit of using the shorthand version unless you have reason to do otherwise, as it will shorten your CSS file.

Horizontal centering

Use margins to center a block element horizontally. Do this by entering 'auto' for the left and right margins. You can see this in the example in the boxes below.

Longhand

	
.classname {
	margin-top: 2%;			 
	margin-right: auto;			 
	margin-bottom: 0;			 
	margin-left: auto;
	padding-top: 4%;			 
	padding-right: 1%;			 
	padding-bottom: 2%;			 
	padding-left: 0;	
	}				
			

Shorthand

	
.classname {
	margin: 2% auto 0 auto;
	padding: 4% 1% 2% 0;	
	}