More on CSS Margins

The properties for CSS margins are used for defining the spaces surrounding an element. The margin clears out an area around an element which is outside of the border. The margin is transparent so it would just be a clear space on the page. The different sides of the margin can be controlled and set to different values independent of each other.

Values Used in CSS margins

Here are some of the possible values that could be used in margins:

    • auto- By using auto, you are letting the browser define the margin that it would display.
    • length- Defines the length of the margin. It can be defined using pixels or some unit of measurement. The default value is set at 0px.
    • %- Using this means you are defining a margin based on the width of the element.
    • inherit- This means that the margin should just follow the element for which it is being used.


As we have mentioned, it is possible to set the sides of the margin independently from each other. Here is a sample code for that:


There is a way that you can shorten the code for the margin property. Here is an example of that:

margin:100px 45px;

From Four to One

It is possible to have one to four values for the margin property.

margin:35px 50px 75px 100px;

Top margin is set at 35px

Right margin is set at 50px

Bottom margin is set at 75px

Left margin is set at 100px

margin:45px 50px 75px;

Top margin is set at 45px

Right and left margins are 50px

Bottom margin is set at 75px

margin:25px 50px;

Top and bottom margins are set at 45px

Right and left margins are set at 50px


All four margins are set at 25px

The CSS Padding

Now something similar but altogether different is the CSS padding. This would refer to the distance between the element and the border that surrounds it. Keep in mind that most of the time, the same rules that you have been using for margin is also applicable to the padding. Here is an example:

      • padding-top: percentage length;
      • padding-left: percentage length;
      • padding-right: percentage length;
      • padding-bottom: percentage length;


There are two ways that you can set the padding. You can use an actual measurement of length such as that in pixel or you can use percentage value instead. Just as there is a shorthand way of declaring the margin value, the same thing could be said of the padding value. When you declare padding on one side only, then that single declaration would be used on the remaining three sides as well. If you declare two padding sides then the opposite value would take effect on the undeclared sides. Not setting the value would let it revert back to 0.

These are just a few of the things that you have to learn when it comes to setting the margin and the padding of an element that you are using.