Apply Margin on a Given Side

Download css eBook

Example

Direction-Specific Properties

CSS allows you to specify a given side to apply margin to. The four properties provided for this purpose are:

  • margin-left
  • margin-right
  • margin-top
  • margin-bottom

The following code would apply a margin of 30 pixels to the left side of the selected div. View Result

HTML

<div id="myDiv"></div>

CSS

#myDiv {
    margin-left: 30px;
    height: 40px;
    width: 40px;
    background-color: red;
}
ParameterDetails
margin-leftThe direction in which the margin should be applied.
30pxThe width of the margin.

Specifying Direction Using Shorthand Property

The standard margin property can be expanded to specify differing widths to each side of the selected elements. The syntax for doing this is as follows:

margin: <top> <right> <bottom> <left>;

The following example applies a zero-width margin to the top of the div, a 10px margin to the right side, a 50px margin to the left side, and a 100px margin to the left side. View Result

HTML

<div id="myDiv"></div>

CSS

#myDiv {
    margin: 0 10px 50px 100px;
    height: 40px;
    width: 40px;
    background-color: red;
}

Stats

Contributors: 3
2016-07-20
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook