CSS Margins

CSS margins are used to create space around elements, outside of their border. Margins push elements away from each other and from the edges of their container.

Margin Properties

The `margin` property allows you to set the margins for all sides of an element or individually for each side.

Margin Shorthand

The `margin` shorthand property sets the margin for all four sides in one declaration. You can provide one, two, three, or four values.


/* Margin shorthand examples */
.box {
    margin: 10px; /* All sides */
}

.card {
    margin: 10px 20px; /* Vertical | Horizontal */
}

.container {
    margin: 10px 20px 30px; /* Top | Horizontal | Bottom */
}

.header {
    margin: 10px 20px 30px 40px; /* Top | Right | Bottom | Left */
}

        

Individual Margin Properties

You can set margins individually for each side of an element using the following properties:


/* Individual margin properties */
.margin-top {
    margin-top: 15px; /* Top margin */
}

.margin-right {
    margin-right: 20px; /* Right margin */
}

.margin-bottom {
    margin-bottom: 25px; /* Bottom margin */
}

.margin-left {
    margin-left: 30px; /* Left margin */
}

        

Auto Margins

The `margin: auto` property can be used to center block elements horizontally within their container.


/* Centering with auto margins */
.centered {
    width: 50%;
    margin: 0 auto; /* Center horizontally */
}