Introduction
Margins in CSS are used to create space around elements, outside of any defined borders. They play a vital role in controlling the layout and spacing of HTML elements on a web page. By adjusting margins, developers can ensure content is well-spaced, visually balanced, and responsive across different devices.

In this article, we will learn how CSS margins work, the various properties involved, and how to effectively use them in web design.
Recommended Topic, Difference Between CSS and SCSS
Margin Values
The first way of assigning margin values comes from the fundamental margin shorthand property, where we can directly give the four margin values.
Example 1 :
|
The four values assigned in the example have the following structures :
- 35px for the Top Margin
- 60px for the Right Margin
- 25px for the Bottom Margin
- 100px for the Left Margin
Example 2 :
Considering the example mentioned above, we can also have a situation where we have only three values assigned. How does that work? Let's have a look!
|
The three values assigned in the example have the following structures :
- 35px for the Top Margin
- 60px for the Right and Left Margin
- 25px for the Bottom Margin
Example 3 :
Three values were easy to understand, but what if we have only two assigned? Sounds a little interesting! Let's see how the two values will be taken into consideration.
|
The two values assigned in the example have the following structures :
- 35px for the Top and Bottom Margin
- 60px for the Right and Left Margin
Example 4 :
Final Task! Now we have only one value assigned! This would be easy to understand, considering that you read the first three examples correctly. Have a look at the code.
|
The value assigned in the example has the following structure :
- 35px for all the margins now. (Top, Right, Left, Bottom)
Now we have a total of 4 ways that we can use to assign the margin values in our CSS sheet. The four ways are explained below :
VALUE | DESCRIPTION |
Length | Used to hardcode the margin taking values in px,pt,cm etc. The default value is 0px. |
Percentage (%) | Used to specify the margin length using the percent of the width of the parent elements. |
Auto | Allows the browser to decide the margin value. |
Inherit | This inherits the margin length from the parent element. |
Example
|
Let’s discuss some of the properties of the individual sides of margins and understand how they work!