Fitting an image in a div, when the div doesn't have defined width/height
Hi everyone.
The issue I sometimes face is that lets say i have a grid of 2 cols 1 row. on the left side i have text content and the right side is a div with an image inside.
If I want the height of the grid to be determined by the text content on the left side, and I set the image to 100% width and height, what ends up happening is that the image expands the grid and determines the grid's height. The only way I can avoid this is by having the image as the background of the div instead. What would be the better approach if I want to use the image?
15 Replies
set a max width/height instead. That way it will grow to be no bigger than it's intrinsic size, but won't necessarily. If there's no room for it to grow (like the grid has a size of some kind) then it just won't.
hmmm, but if the image is oringially small than the parent container and i want it to stretch (object fit cover) to fill the container, do i set height width max-height max-width to 100% or how does it work
You want to stretch the image? That sounds…not so great. Pixilation will occur
like an svg that has a default size of 16 px
Why do you want to enlarge a 16x16 image? I feel like this is an x/y problem
ok i'll give a more realistic example to get my message across. say an image has an aspect ratio such that it'll fill the height of the container but it will be lacking in width. i want it to cover the full container without stretching it
You're describing the outcome you want, not why. And that's what I'm asking for. What is the reason you want to pixilate the image? Why can't it just stay it's normal dimensions?
the image is big enough to not pixelate, but it is restricted due to aspect ratio to not full the width of the container, just the height
Here's an example to clarify my point:
https://jsfiddle.net/8wdp49xu/
The image is humongus, and i just want it to fill the parent div
so it's not an issue of pixellation
seems setting max-width to 100% but height to 100% fixed it, while having only max-width and max-height 100% didnt fill the div
Also throw in
object-fit: cover;
That way it'll scale (but keep the aspect ratio) to fill the container.so specifying height or width to 100% is critical for this to work
Might need to play with object position, too, to make sure the correct parts of the image are in view
Yes.
max-width
and height
I think are necessary. And most certainly not max-height
. Fixed height is best for thisthanks so much! out of curiousity, when is it acceptable to use an image as a div background, instead of inserting image into a div
Usually you use a background image when it's not materially important. They're used for emphasis or purely visual "fun".
For example, if you're making a shopping site, you don't use background images you use real image tags so you can have alt text and whatnot.
ahhhh got it
makes sense 🙂 thank you !!
Sure thing!