CSS MARGINS


In CSS, margins are needed to create space around elements outside of any defined borders.

CSS margin property is used to assign values of margins, either one by one or using shorthand method. The shorthand method is preferred as it makes the code short and clean.

Shorthand assignment has top, right, bottom, and left properties.

Values can be assigned to these properties in the form of length specified in px (pixels), cm & pt. It is also specified in the form of % of width of the containing element or in the form of inherit. In this case the element inherits the margin from parent element. While defining margins, negative values can be assigned.


Syntax:


div {
  margin-top: 50px;
  margin-bottom: 50px;
  margin-right: 150px;
  margin-left: 80px;
}

Live Demo!


Implementation in an html page:


<!DOCTYPE html>
<html>
<head>
<style>
div {
  border: 1px solid black;
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 150px;
  margin-left: 80px;
  background-color: rgb(240, 166, 191);
}
</style>
</head>
<body>

<h2>Using individual margin properties</h2>
<div>top margin 100px, right margin 150px, bottom margin 100px,
a left margin 80px.</div>

</body>
</html>

Live Demo!


Output:

Using individual margin properties

top margin 100px, right margin 150px, bottom margin 100px, a left margin 80px.


Syntax For Shorthand


Shorthand method is a better approach for specifying margins. Here's an example:


div{
  margin: 75px 50px 75px 50px;
}



Let's see an example of shorthand assignment in an html document:


<!DOCTYPE html>
<html>
<head>
<style>
div {
  border: 1px solid black;
  margin: 75px 50px 75px 50px; /* Shorthand Method */
  background-color: rgb(193, 240, 166);
}
</style>
</head>
<body>

<h2>The margin shorthand property - 4 values</h2>
<div>Top margin 75px, right margin 50px, bottom margin 75px,
left margin 50px.</div>

</body>
</html>

Live Demo!


Output:

The margin shorthand property - 4 values

Top margin 75px, right margin 50px, bottom margin 75px, left margin 50px.


If the margin property has three values:


p {
  margin: 25px 50px 75px;
}

Live Demo!


  • top margin is 25px
  • right and left margins are 50px
  • bottom margin is 75px

If the margin property has two values:


p {
  margin: 25px 50px;
}

Live Demo!


  • top and bottom margins are 25px.
  • right and left margins are 50px.

If the margin property has one value:


p {
  margin: 25px;
}

Live Demo!


  • All four margins are 25px.

The auto Value


margin:auto is used to horizontally centre the element within its container.
The element takes up the specified width, and the remaining space is split equally between the left and right margins.


div {
  width:300px;
  margin: auto;
  border: 1px solid red;
}

Live Demo!