How to use Margin in CSS?

devashishsethi

dev-ashishsethi

Posted on December 3, 2021

How to use Margin in CSS?

According to box model in CSS margin is the outer most edge of any element, it can be set on all the four sides of the element. It can be written in shorthand or assigning different values to individual margin properties for example, margin-top:10px, margin-right:20px, margin-left:2px, margin-bottom:8px.

Writing margin in shorthand

For writing margin in shorthand there are some things to learn first, let me tell what those are.

In shorthand you can specify only one value or two values or three values or four values.

One Value

example-> margin: 2rem;
It applies same measurement(2rem here) to all the four sides.

Two Values

example-> margin: 2rem 4rem
First value gets applied to top and bottom and second value gets
applied to left and right of element.

Three Values

example-> margin: 2rem 4rem 1rem;
First value applies to top, second value applies to right and
left and third value applies to bottom.

Four Values

example-> margin: 2rem 4rem 3rem 1rem;
First value gets assigned to top, second values is assigned to
right, third values gets assigned to bottom and fourth value gets
assigned to left.

đź’– đź’Ş đź™… đźš©
devashishsethi
dev-ashishsethi

Posted on December 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related