Search code examples
htmlcssflexbox

CSS: Make image fill parent but not change parent size


I have an image gallery and all of the images are squares. The images are in their divs and a big div with the display to flex to parent all the divs. I want the images to fill their parent div, but not make them bigger.

UPDATE: I saw on this website that the flex-grow property does NOT add to the (usable) width of the element. Go see the website for a further explanation, but that means I have to use something else than flex-grow to make my parent divs the width of the top div.
Also, I do not want a fixed amount of items on a line!! What I want is when you scale up the window, the elements get wider and wider until a point, where you then shrink the elements and add one from under to the line above.

Here is what I have: What I have:

Here is what I want: What I want:

Here is my code:

.ImagesContainer {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: .25rem;
    margin-top: 1rem;
    width: 100%;
}

.ImagesContainer img {
    width: 20vw;
    min-width: 200px;
    margin: 5px;
    transition-duration: 200ms;
}

.ImagesContainer div {
    background-color: red;
    flex-grow: 1;
}
<div class="ImagesContainer">

  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>
  <div> <img src="https://picsum.photos/200"> </div>

</div>

Does anybody have an idea?


Solution

  • UPDATE: The method I was using (With flexbox) did not do what I wanted finally so I decided to use css grid and it did it perfectly!
    Here is the new css (same html):

    .ImagesContainer {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: .25rem;
        width: 100%;
    }
    
    .ImagesContainer img {
        width: 100%;
        height: 100%;
    }
    
    .ImagesContainer a {
        padding: 5px;
    }
    

    Thank you to everyone, your answers helped me understand css better!