{"id":14069,"date":"2011-09-05T20:48:43","date_gmt":"2011-09-06T03:48:43","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=14069"},"modified":"2021-09-21T15:18:41","modified_gmt":"2021-09-21T22:18:41","slug":"margin","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/properties\/m\/margin\/","title":{"rendered":"margin"},"content":{"rendered":"

The margin<\/code> property defines the outermost portion of the box model, creating space around an element, outside of any defined borders.<\/p>\n

Margins are set using lengths, percentages, or the keyword auto<\/code> and can have negative values. Here’s an example:<\/p>\n

.box {\n  margin: 0 3em 0 3em;\n}<\/code><\/pre>\n

margin<\/code> is a shorthand property and accepts up to four values, shown here:<\/p>\n

.box {\n    margin: <margin-top> || <margin-right> || <margin-bottom> || <margin-left>\n}<\/margin-left><\/margin-bottom><\/margin-right><\/margin-top><\/code><\/pre>\n

If fewer than four values are set, the missing values are assumed based on the ones that are defined. For example, the following two rule sets would get identical results:<\/p>\n

.box {\n  margin: 0 1.5em;\n}\n\n.box {\n  margin: 0 1.5em 0 1.5em;\n}<\/code><\/pre>\n

Thus, if only one value is defined, this sets all four margins to the same value. If three values are declared, it is margin: [top] [left-and-right] [bottom];<\/code>.<\/p>\n

Any of the individual margins can be declared using longhand, in which case you would define only one value per property:<\/p>\n

.box {\n  margin-top: 20px;\n  margin-right: 10px;\n  margin-bottom: 20px;\n  margin-left: 10px;\n}<\/code><\/pre>\n

auto<\/code> and centering<\/h3>\n

Each of the margin properties can also accept a value of auto<\/code>. A value of auto<\/code> basically tells the browser to define the margin for you. In most cases, a value of auto<\/code> will be equivalent to a value of 0<\/code> (which is the initial value for each margin property) or else whatever space is available on that side of the element. However, auto<\/code> is handy for horizontal centering:<\/p>\n

.container {\n  width: 980px;\n  margin: 0 auto;\n}<\/code><\/pre>\n

In this example, two things are done to center this element horizontally within the available space:<\/p>\n