Streaming live at 10am (PST)

Maintain Image Aspect Ratio when Filling a Div

I’m trying to make an image stay within its DIV without changing the image’s aspect ratio. The DIV is set to “Stretch” as a flex item so that I can contain the image inside without it overflowing, however when I do so, the image’s aspect ratio gets funky.

This is what the image should look like:

But when I expand the screen, the image responds but overflows:

I tried to fix the issue by having the image “Stretch” in a flex layout, so it doesn’t overflow anymore, but now the image’s aspect ratio is messed up:

Please help!


Here is my public share link: LINK

1 Like

Fluid images

Most famous/supported way for responsive images is this code (fluid images):

  width: 100%;
  height: auto;

By the way this trick was one of three layers of responsive design when Ethan Marcotte coined this term “responsive web design” in 2010:

Should work fine.

Today You have a lot more ideas/tricks but not all - well supported - object-fit for example. See this Q to get more ideas:

Your case:

  1. change Image Section to display block (no need for nested flex grid her - see “extra nested” later).
    If you also want all to center vertical see this tutorial (add the “align-center” flex option toFlex Section)
  2. Change image to width: 100 - height: auto
  3. Set Flex Section height to bemin:100vh --> remove 100vh from the section-wrapper (you want align items relative to 100vh of flex-section)

Extra Nested

flex-parent (wrraper) vs flex-child (col): In your code you add endless time display:flex (for parent-child-child) this create nested-grids and very hard to style code. Most of the time the parent is display:flex and the child-wrapper is block (if you also set the child to display flex - is for nested grid and complex layout).

Example of time you need nested grid:

Follow the examples her to learn this issue:

columns vs flexbox

For very simple layout its better to work with flexbox grid columns). The main reason its more easy to control responsive layout like this.

HTML5 elements

Out of topic: For more clean/semantic code: Change section to really be sections :slight_smile:


That really helped. Thank you so much!

1 Like

You welcome. Mark as solved to close this topic (and for future searches). Thanks :slight_smile:

This topic was automatically closed 125 days after the last reply. New replies are no longer allowed.