How to change margin of Div using CSS?

Answer

To change margin of Div using CSS, you can set the margin style property for the div elements with the values like 20px, 2rem, 1.1in, etc.

CSS Code

The following is the typical CSS code to change margin of Div in HTML page using tag name div.

Using pixels for margin

div {
   margin: 20px;
}

Using margin relative to parent dimensions

div {
   margin: 2rem;
}

Using inches for margin

div {
   margin: 1.1in;
}

Examples

We shall go through some working examples on how to change margin of Div using CSS. In the following examples, you may change the value of margin and Run the code to visually observe the changes made to the Div elements.

Example 1

This is an example on how to change margin of Div using pixels for margin.

You may edit the following code, and click on Run button.

Example 2

This is an example on how to change margin of Div using margin relative to parent dimensions.

You may edit the following code, and click on Run button.

Example 3

This is an example on how to change margin of Div using inches for margin.

You may edit the following code, and click on Run button.