CSS Margin

The margin property in CSS is used to create space around an element, outside of any defined borders. It can be used to set the margin for each side of an element (top, right, bottom, and left), or for all four sides at once.


margin and padding

Basic Margin Syntax

The CSS margin property is used to set the margin for all four sides (top, right, bottom, left) of an element. The basic syntax is as follows:

        
            selector {
    margin: top right bottom left;
}
        
    

Information

You can set the margin using different units such as pixels (px), ems (em, rem), percentages (%), and more.


Setting Uniform Margins

If you want all four margins to have the same value, you can simply provide one value:

Try yourself
        
            div {
    margin: 20px; /* Applies 20px margin to all sides of the div */
    background: red;
    width: 400px;
    height: 400px;
}
        
    

Setting Vertical and Horizontal Margins

If you want to set the top and bottom margins to one value, and the right and left margins to another value, you can use the following syntax:

Try yourself
        
            div {
    margin: margin: 10px 20px; /* Top and bottom have 10px margin, left and right have 20px margin */
    background: green;
    width: 400px;
    height: 400px;
}
        
    

Setting Individual Margins

You can also set margins for each side individually:

Try yourself
        
            div {
    margin-top: 30px;
    margin-right: 10px;
    margin-bottom: 20px;
    margin-left: 5px;

    background: green;
    width: 400px;
    height: 400px;
}
        
    

Mixing Shorthand and Individual Margins

You can mix shorthand and individual margin properties. When using shorthand, any individual margin properties not specified will be set to their default value (usually 0).

Try yourself
        
            div {
    margin: 10px 20px; /* Top and bottom have 10px margin, left and right have 20px margin */
    margin-bottom: 30px; /* Override the shorthand and set the bottom margin to 30px */

    background: green;
    width: 400px;
    height: 400px;
}
        
    

Auto Margins

You can use auto in the shorthand property to horizontally center a block-level element within its container.

Try yourself
        
            .container {
    width: 800px; /* Set the width of the container */
    height: 800px;
    background: green;
}

.centered-content {
    width: 400px; /* Set the width of the element you want to center */
    height: 400px;
    margin: 0 auto; /* Horizontally center the element within the container */
    background: blue;
}

        
    

Negative Margins

Negative margins are used to overlap elements or reduce the space between them. Exercise caution when using negative margins, as they can lead to unexpected layouts.

Try yourself
        
            div {
   margin: -10px 0 0 -10px;
   background: blue;
   width: 400px;
   height: 400px;
}