CSS Margin

In CSS, the margin property controls the amount of space outside an element's border. It determines the space between the element and other elements on the page. Margins are transparent and can be set for all sides of an element or individually.


Syntax:

margin: <value>;


Value: Can be a length (e.g., px, em, %), auto, or inherit.

Example
div {
margin: 50px;
}

Try it yourself

Individual Margins:

You can specify margins for each side of the element using these properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left
Example
div {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}

Try it yourself

Shorthand for Margins:

You can also use shorthand to specify margins for different sides in one declaration:


Syntax:

margin: <top> <right> <bottom> <left>;
Example
div {
margin: 10px 20px 30px 40px;
}

Try it yourself

Auto Margins (Centering Elements):

One powerful feature is margin: auto;, which can be used to center block-level elements (like div) horizontally within their container when they have a set width.

Example
div {
width: 300px;
margin: 0 auto; /* Vertically no margin, horizontally centered */
}

Try it yourself

Margin Collapsing:

In CSS, vertical margins (top and bottom) between block elements may collapse, meaning the larger of the two margins is used instead of adding them together.

Example
.first {
margin-bottom: 50px;
}
.second {
margin-top: 30px;
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.