Forum Moderators: not2easy

Message Too Old, No Replies

Responsive width and height of image

         

csdude55

5:16 pm on Jan 24, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a container with several images that are positioned on top of one another, like this:

<div style="position: relative; width: 600px; height: 550px">
<img src="img_1.gif" width="600" height="550"
style="position: absolute; top: 0; left: 0; z-index: 1">

<img src="img_2.gif" width="600" height="550"
style="position: absolute; top: 0; left: 0; z-index: 2">

<img src="img_3.gif" width="600" height="550"
style="position: absolute; top: 0; left: 0; z-index: 3">

<img src="img_4.gif" width="600" height="550"
style="position: absolute; top: 0; left: 0; z-index: 4">
</div>


But to be mobile friendly I REALLY want the width to be 100%, max-width: 600px, and height to be proportionate to the width.

What's the correct / most backwards compatible way to do this? I'm thinking:

<div style="position: relative; max-width: 600px; width: 100%; height: auto">
<img src="img_1.gif"
style="position: absolute; top: 0; left: 0; z-index: 1;
width: auto; height: auto">

...
</div>

lucy24

8:03 pm on Jan 24, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I think you need to set one of the values to a percentage, like max-width: 95% and height: auto (or vice versa, depending on the size & shape of your images). If you set one value to "auto" the browser will, or should, interpret it as "proportional to the other value"-- but if you set both to "auto" the browser will probably keep it at full size.

not2easy

8:12 pm on Jan 24, 2020 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



If you are setting the size of the <div> element, the image can be set to max-width: 100% - and lucy24 is right, you shouldn't set both height and width to" auto" even if it should be constrained by the <div> dimensions.

tangor

9:55 pm on Jan 25, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I keep it a bit more simple in setting img to auto in the css style sheet and all images react properly to whatever container the image appears ... thus I only deal with the divs for size, not the images.

YMMV