CSS Margin Property
The margin property in CSS is used to create space around elements, outside of any defined borders. It is a key component of the CSS Box Model and is essential for layout spacing.
The Box Model Context
Every element in CSS is a box. From the inside out, it consists of: Content, Padding, Border, and Margin. Margin is the outermost layer, transparent and invisible, used to push other elements away.
Shorthand Syntax
You can specify margins for each side individually or use shorthand to save time:
- 1 Value:
margin: 20px;(All sides) - 2 Values:
margin: 10px 20px;(Top/Bottom, Left/Right) - 3 Values:
margin: 10px 20px 30px;(Top, Left/Right, Bottom) - 4 Values:
margin: 10px 20px 30px 40px;(Top, Right, Bottom, Left - Clockwise)
Margin Collapsing
Top and bottom margins of adjacent elements sometimes collapse into a single margin that is equal to the largest of the two margins. This does not happen on left and right margins.
Auto Margins
Setting margin: 0 auto; on a block element with a defined width is the standard way to center it horizontally within its container. The browser calculates the available space and distributes it equally to the left and right.
