Defining Element Margins - HTML

Margins are an important issue to consider when designing documents. Some elements have built-in margins to separate themselves from adjoining elements. However, sometimes you will find that you need to increase (or decrease) the standard margins.

For example, when using images, you may find the margin between the image and the surrounding elements too slim. Notice that the “T” is all but touching the image. Note that the following code was used to separate the two elements:

<img src=“square.png” style=“float: left;”><p>Text next to an image</p>

You can use the margin properties to adjust the space around an element. There are properties to adjust each margin individually, as well as a shortcut property to adjust all the margins with one property.

The margins on some elements are too tight, as shown by how close the text is to theimage.

The margins on some elements are too tight, as shown by how close the text is to the image.

The margin-top, margin-right, margin-bottom, and margin-left properties adjust the margins on individual sides of an element. The margin property can adjust one side or all sides of an element. The margin properties all have a simple format:

margin-right: width;

The margin shortcut property allows you to specify one, two, three, or four widths:

margin: top right bottom left;

For example, suppose you want to set the margins as follows:

  • Top: 2px
  • Right: 4px
  • Bottom: 10px
  • Left: 4px

You could use this code:

margin: 2px 4px 10px 4px;

Tip: You don’t have to specify all four margins in the margin property if some of the margins are to be set the same. If you only specify one value, it applies to all sides. If you specify two values, the first value is used for the top and bottom, and the second value is used for the right and left sides. If three values are given, the top is set to the first, the sides to the second, and the bottom to the third.

So let’s return to the example in Figure, where the text is too close to the image. You can separate the two elements by increasing the right margin of the image, or the left margin of the text. However, you probably would not want to increase any of the other margins.

Tip: There are no real guidelines when it comes to which margins to adjust on what elements. However, it’s usually best to choose to modify the least number of margins or to be consistent with which margins you do change.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

HTML Topics