Positioning and Fitting Images in Element’s Box with CSS

It is also possible to align an image within an element’s box as well as specify how to fit it in the box. The property for aligning is object-position and the one for fitting is object-fit.

1. object-position

The object-position property lets you specify the position of an image (or any object, including video) relative to the edges of the element’s box. It is inherited and the values it takes are x-y coordinates of where to position an image. The values are expressed in length values and can be in absolute length units (e.g., px), box-relative lengths (i.e., %), font-relative lengths (e.g., em), or viewport-percentage lengths (e.g., vh and vw). Positive values move image toward the right or bottom, and negative toward the left or top. Figure 15.11 shows how the property is used and Figure 15.12 the result.

In the example, the img{} rule specifies the size of the <img> element, the border width, style and color, the background color, and right margin to put some space between the images. The .obj ect-position{} rule positions the <img> element of class=“object-position” 60px from the left edge of the element’s box and 30px from the top edge. Notice that the background of the image is transparent and that is why the element’s background color is visible.

2. object-fit

The object-fit property allows you to specify in a number of ways how the content of an element should be made to fill the element’s content box. Its effect depends on the difference between the aspect ratio of the content and the aspect ratio produced by the specified dimensions for the element’s content box. Aspect ratio is the ratio of width to height (i.e., width:height). The property is non-inherited and the values it takes are listed in Table 15.3. Figure 15.13 shows how the properly is used and Figure 15.14 the effects of the values (not the output of Figure 15.13).

Notice in the example the large differences between the outputs of the values. This is because the aspect ratio of the image (content) is significantly different from that of the element’s content box. The actual size of the image is 800 x 536 pixels, making its aspect ratio 1.49:1 (i.e., 800:536), while the size of the element’s content box is 200 x 70 pixels, making its aspect ratio 2.86:1 (i.e., 200:70). The reference image represents the image displayed without object-fit.

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 *