Margin with CSS

The margin property is a shorthand property for specifying the amount of space around the outer edge of an element’s box and serves to separate one box from another. Like the padding property, it is non-inherited and has the initial value of 0. It also takes one to four space-separated values, which can be in length values (e.g., px and em), percentage values, or auto keyword. If percentage is used, the value is relative to the width of the containing element’s box. The auto keyword leaves it to the browser to determine margin values as it sees fit. How values are assigned is explained in Table 10.13.

The longhand properties of the margin property are margin-top, margin- right, margin-bottom, and margin-left. Figures 10.54 and 10.55 show how the shorthand property is used and depict the effects.

In the example, the first rule applies to all <p> elements, while each of the remaining rules applies to individual <p> elements of matching class. Note that setting margin to auto, as done in the example, horizontally centers a box in the browser window or inside the element’s box that it is in. As mentioned earlier, if width is not specified, a box occupies the full width of the page, making it impossible to center it. Notice in the example that the text is not centered in the box. To do this, you need to use the text- align property, discussed in Chapter 14.

1. Specifying Margin for Logical Edges

The properties used to specify margin for the logical edges of an element are margin-block-end, margin-block-end, margin-block-end, and margin- block-end . Whether each defines the top, bottom, left, or right edge of an element depends on the value of the writing-mode property (discussed in Chapter 14). The properties are non-inherited and take the same values as the margin-top, margin-right, margin-bottom, or margin-left property. Figure 10.56 shows example of how the properties are used, and Figure 10.57 depicts the result. Given the writing mode, margin-inline-start defines the left edge.

2. Margins in Design

Margins essentially help provide contrast and visual interest, because they form a frame of negative space around the content of a page. This can add to the aesthetics of a layout and also makes text easy to read, since it reduces, for example, the width of text (i.e., number of characters per line). Figure 10.58 shows some illustrations. Notice the differences in the “airiness” of the pages. Most would say that the ones on the right are more aesthetically pleasing.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *