Responsively Center an Image and Caption with CSS Grid

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Grid offers us the easiest method to responsively center content. We'll use the grid property place-content to center the contents of figure to showcase our fictional product in use. Additionally, we'll learn about object-fit which is a modern technique that allows inline images to scale responsively within defined dimensions without distortion.

Instructor: [0:00] Our product showcase is marked up using the figure element. Let's begin the figure rule by clearing the margin inherited from browser styles and adding a height and background color to help to define the section. For the background color, we use the SAS function for scale color to obtain a lighter version of our theme's primary color.

[0:23] We also set the height using VH, which means this will take up up to 90 percent of the currently available viewport height. Within the figure rule, we'll add styles for image. We'll set object-fit cover, which results in our inline image behaving more similarly to a background image, particularly when we add width and height rules.

[0:48] Object-fit cover directs the image content to scale and fill the set dimensions without experiencing distortion. Again, we have used viewport units to set a max height of 60 view heights and a width of 80 view widths. A slight border radius and box shadow are also added for visual effect.

[1:09] Now it's time to focus on the section layout. We'll start by applying our existing class of display-grid. Something interesting has happened, which is that the grid algorithm which defaults to placing grid items in rows has assumed how much space to a lot the image versus the figcaption. We can see this better by using inspector, which reveals the grid areas.

[1:37] Our goal is to responsively center the image and the caption as one unit, both vertically and horizontally. We can accomplish this with a modifier class for display-grid, which we'll name place-center and defined a single property, place-content center. Then, we'll apply that to the figure and save.

[2:01] To wrap up, let's fix the text contrast and vertical alignment of the figcaption. We'll add a rule for figcaption with just one property for color, set to white, and then use some existing utility classes to bump up the font size, apply text align center, and adjust the margins.

[2:21] If we test resizing the viewport, we see that the image dimensions responsively scale. The image and caption keep vertically and horizontally centered within the figure layout.

[2:35] To accomplish our main goal of centering the figure content, only require the use of display-grid and place-content center. Viewport units assisted in general sizing of the layout contents. Object-fit cover allowed the image to be responsive within defined dimensions without distortion.