htmlcssflexbox

Images overflowing beyond div instead of shrinking


I pretty new to html coding so I'm not sure what I'm doing wrong, but I'm building a website with an image gallery on one of the pages.

I wanted half of the gallery to be a flex row with wrapping (flex-flow: row wrap;) for wider images and the other half set to nowrap so that the smaller images are side by side. Both galleries' images have the width set to 100% so that the images "shrink" to fit the div of the gallery.

I've tried this multiple times, like putting the second div gallery outside the first, having them separate, using fit-content, max-width to 100%, etc. They only way to make it smaller is if I manually shrink it with something like width=50%, but I don't want to set a fixed size because I want them to be responsive.

Here's the code for reference:

.page-content {
  display: flex;
  flex-flow: column;
  justify-content: center;
  grid-gap: 20px;
  max-width: 850px;
}

.gallery img {
  border-radius: var(--corner-rounding);
  max-width: 100%;
}

.gallery {
  display: flex;
  flex-flow: row wrap;
  grid-gap: 1em;
  align-items: baseline;
  justify-content: center;
}

.line {
  display: flex;
  flex-flow: row nowrap;
}
<section class="page-content">
  <div class="gallery">
    <img src="img/gb01.gif" />
    <img src="img/gb02.gif" />
    <img src="img/gb03.gif" />
    <img src="img/lvl1.jpg" />
    <img src="img/lvl2.jpg" />
    <img src="img/lvl3.jpg" />
    <div class="gallery line">
      <img src="img/sreenshot01.jpg" />
      <img src="img/sreenshot02.jpg" />
      <img src="img/sreenshot03.jpg" />
    </div>
  </div>
</section>

Any idea what I should do about this?

EDIT: I said above that I've already tried putting the second gallery (.line) outside the first gallery (.gallery) and it didn't work. However, I now realize that is because the section both galleries are nested in is also set to flex. Oops.

Now, while I waited for this answer I went and tried making the second gallery a grid display with auto columns. In terms of best practices, is this okay or should I be avoiding this?

.line {
  display: grid;
  grid-auto-flow: column;
}

Thanks to everyone who answered :^)


Solution

  • Move the second gallery (.gallery.line) outside of the first .gallery div so both galleries can have their own layout behavior. Also, make sure to apply responsive CSS rules to keep the images within their container.

    Try this ->

    <section class="page-content">
      <div class="gallery">
        <img src="img/gb01.gif" />
        <img src="img/gb02.gif" />
        <img src="img/gb03.gif" />
        <img src="img/lvl1.jpg" />
        <img src="img/lvl2.jpg" />
        <img src="img/lvl3.jpg" />
      </div>
    
      <div class="gallery line">
        <img src="img/screenshot01.jpg" />
        <img src="img/screenshot02.jpg" />
        <img src="img/screenshot03.jpg" />
      </div>
    </section>