Aligning Images with CSS

Aligning images usually refers to aligning them horizontally along the width of the browser window, since the height of a page is very arbitrary. Although this used to be done using the HTML align attribute on the <img> element, this is no longer recommended and not supported in HTML5. Instead, this goal is accomplished using CSS properties. What is required to center an image depends on whether or not the <img> element that contains the image is inside the <figure> element. If it is, then the <figure> element needs only be centered like any block level element, since it is one. If it is not, then the <img> element first needs to be turned into a block level element, using the display property. This is because the <img> element is an inline element and therefore flows with text as if it is just another word. Centering a block basically involves making the margin on either side of it equal, and the most efficient way to do this is to set margin-left and margin- right to auto, so that the browser determines the values to use. Figure 15.9 shows how to do this and Figure 15.10 the result.

The img{} rule in the example sets the width and height of the image, changes the <img> element to a block-level element, and sets the right and left margins. Note that a declaration using the margin shorthand property (thus: margin: 0 auto) will produce the same result.

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 *