Margins, Padding, and Centering

Sometimes, you don’t want to position an element solely based on its personal position - rather, you want to position it relative to other elements. This is where margin comes into play. By setting the margin, you can ensure that the element will be a specified distance from other elements on the top, right, bottom, or left side. Here’s an element with all of the margins specified individually:

	
a {
	margin-top: 5px;
	margin-right: 10px;
	margin-bottom: 5px;
	margin-left: 10px;
}
	

The sequence of sides in the example above (top, right, bottom, left) is directly related to the shortcut “margin” property, in which all sides can be specified. The following is equivalent to the four properties above:

	
a {
	margin: 5px 10px 5px 10px;
}
	

Margin introduces a distance between objects. In contrast, padding causes a distance inside of an element, in between its border and its content. It can also be specified either one side at a time, or all at once.

	
a {
	padding-top: 5px;
	padding-right: 10px;
	padding-bottom: 20px;
	padding-left: 10px;
}

p {
	padding: 5px 10px 20px 10px;
}
	

One use of margin is to help center items on the screen. In old Internet Explorer browsers, you could center content by declaring “text-align: center” in the parent element, usually <body>. This is not an optimal way to center block elements, however. If you’re using “position: relative”, the best way to center elements is as follows:

	
div#centerDiv {
	position: relative;
	margin-left: auto;
	margin-right: auto;
	width: 800px;
	height: 400px;
}
	

This will horizontally center the <div> on the page. Another way to center items involves “position: absolute”. You set the left of the element to 50%, and set the margin-left to -(width / 2)px, like so:

	
div#absoluteCenter {
	position: absolute;
	left: 50%;
	width: 800px;
	margin-left: -400px;
}
	

Finally, if you want an item centered both horizontally and vertically, you can do the following:

	
div#totallyCentered {
	position: absolute;
	left: 50%;
	width: 800px;
	margin-left: -400px;
	top: 50%;
	height: 400px;
	margin-top: -200px;
}