0

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 do 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)

<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%
}
DominicT
  • 388
  • 1
  • 9
  • @Martin actually I would like to know why i need to do one more step(setting the container B) for the height but no need for the width.I want to figure out the reason behind it. – Vergil Chan Apr 27 '23 at 16:00
  • The Width value is the primary value because a webpage has an infinite height but only a set limited width. therefore width is always the primary dimension on these things – Martin Apr 27 '23 at 16:18

2 Answers2

0

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

La Dio
  • 3
  • 2
0

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;
}
Vishal
  • 1
  • 1