Content of the div adjusting to its size?

Asked

Viewed 442 times

1

I have a div that controls the maximum size an image can have. I would like the image to fit the size of the div, without cutting part of it (as in overflow: hide).

I used the overflow:hide the image does not exceed the limit of the div.

HTML:

<div id="controlImg">
    <img src="img/arroz.jpg">
</div>

CSS:

#controlImg{
max-width: 400px;
max-height: 500px;
border: 1px solid green;}

#controlImg img {
    width: 100%;
    height: 100%;
}

In the overflow: auto, a scroll bar is created instead of cutting the image, but I would really like it to adapt to the size of the parent div (controlImg)

In the image, I inserted width:100% and height:100%, but the image did not obey, as shown in the image: inserir a descrição da imagem aqui

  • max-width: 100%; max-height: 100%;

1 answer

0


Can use a width: 100% for the image to occupy the full width of the parent element:

#controlImg {
    max-width: 400px;
    max-height: 500px;
    border: 1px solid red
}

#controlImg img {
  width: 100%
}
<div id="controlImg">
    <img src="https://picsum.photos/900">
</div>

Or using as background of the element:

div {
  width: 500px;
  height: 400px;
  border: 1px solid red
}

.rice {
  background: url(https://i.stack.imgur.com/6Jgo0.jpg); 
  background-size: 100% 100%
}
<div class='rice'></div>

  • Renan thanks for the reply. I did so, and still added the height 100%, but it did not work, as in the image I inserted

  • If you are going to apply the size in height (instead of width), your parent element should have a defined size (a height and not max-height). And in that case it won’t do any good height and width together with 100%, the image will not "expand" and occupy the whole element, for that you would have to use the image as background of the element.

  • @Weslipe I edited.

  • It worked, but unfortunately it does not fit in what I need, because the image (in the case of rice) will come from the bank, so it will be an image per product, I can not set in css a pattern

  • My mistake was that I was inserting the max height and width into the div, rather than the image. When telling the image that the maximum height and width it should have is 100% relative to the parent, the image behaved well. The code: #modalProduct #controlImg{ border: 1px Solid green; } #controlImg img { /* maximum width and height of 100% of parent div */ max-width: 100%; max-height: 100%; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.