Box Model
CSS Margin
Setting CSS Margins
CSS margins space elements, supporting negative values for overlap.
Introduction to CSS Margin
The CSS margin
property is used to create space around elements, outside of any defined borders. Margins can be used to separate elements from each other or create a clear and organized layout. In CSS, margins can be specified using individual properties for each side (top, right, bottom, left) or with shorthand notation.
Margin Syntax and Shorthand
Margins can be defined using the following properties:
margin-top
margin-right
margin-bottom
margin-left
Alternatively, margins can be set using the shorthand margin
property. The shorthand can take one to four values, which apply to the top, right, bottom, and left sides of an element, respectively.
Negative Margins
CSS margins can also be negative, which allows elements to overlap. Negative margins can be useful in certain layout techniques, such as pulling elements closer together or achieving unique overlap effects.
Auto Margins for Centering
Setting the margin property to auto
is a common technique for centering block elements horizontally within their container. This is especially useful for layouts with fixed widths.
Margin Collapse
When vertical margins meet, they can combine into a single margin instead of adding together. This behavior is known as margin collapse and typically occurs with block elements.
Conclusion
The CSS margin
property is a powerful tool in creating space and positioning elements within a web page. By understanding both positive and negative margins, as well as techniques like auto margins and margin collapsing, developers can effectively control layout and spacing in their designs.
Box Model
- Margin
- Padding
- Border
- Box-Sizing
- Width and Height