Home > Blockchain >  CSS: Make image fill parent but not change parent size
CSS: Make image fill parent but not change parent size

Time:05-09

I have an image gallery and all of the images are squares. The images are in their own personal 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 it bigger.

UPDATE: I saw on What i have:

Here is what i want: What i want:

<div >

  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>
  <div> <img> </div>

</div>

Here is the css:

.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;
}

Anybody has an idea?

CodePudding user response:

You need to give width to image wrapper only and fit the image appropriately. If you want some part of your div be seen, you can add padding property to it. By adding "object-fit: cover" property to your image you can scale it to fit its parent's width, and "object-position: center" in case your image is not square and a part of it gets cut.

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

    .ImagesContainer img {     
        transition-duration: 200ms;
        width: 100%;
        object-fit: cover;
        object-position: center;
    }

    .ImagesContainer div {
        background-color: red;
        flex-grow: 1;    
        width: 20vw;
        min-width: 200px;
        padding: 5px;
    }
    <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> <img src="https://picsum.photos/200"> </div>

    </div>

  • Related