skip to Main Content

I would like to put an image to fit some containers based on the height or the width.

the outer container A have the fixed width and height.

I only need to set the img like width:100% if I want it to be based on the width.
then the image will fit the container. (no need to set the width of the container B)

but why I have to set the height of the container B and the img if based on the height,
otherwise the image will not fit and overflow the container.
(can’t I be like setting the width? ignore the height of container B)

html

<div className="containerA">
      <div className="containerB">
      <img src={abc}/>
      </div>
    </div>

CSS based on the width

.containerA{
    width: 100px;
    height: 140px;
}

img{
   width:100%
}

CSS based on the height

.containerA{
    width: 100px;
    height: 140px;
}

.containerB{
   height:100%
}

img{
   height:100%
}

2

Answers


  1. I think using object-fit: contain; parameter on your img tag might help

    Login or Signup to reply.
  2. To make the image fit inside container B based on the height, you can set the height of container B to a fixed value and set the height of the image to 100%. This will ensure that the height of the image is the same as the height of container B and the image fits inside it. You can also set the width of the image to auto, so that the image maintains its aspect ratio and adjusts its width accordingly. Here is an example of how you can do this:

    .containerA {
      width: 100px;
      height: 140px;
    }
    
    .containerB {
      height: 100px;
      position: relative;
    }
    
    img {
      height: 100%;
      width: auto;
      position: absolute;
      inset: 0;
      margin: auto;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search