When using width:100% the following way in a responsive web design context …
<img src='car.jpg' alt='' style='width:100%;'>
… then the image will fit in the window of the screen or device.
However, when the image is inserted dynamically via a JavaScript-coded database, I’m having trouble getting the image to fit in a small screen. The above 1500px-width image will overflow the small screen rather than fit device-width. Is there a reason for this?
This properly sizes the oversized 1532px image to fit the device width (using your code), apart from the DB:
CSS:
<style type="text/css">
body {
padding:0;margin:0;
}
.image-wrap{width:100%;}/* set min or max-widths as required*/
.image-wrap img{width:100%;height:auto;}
</style>
But when I incorporate the same code with a JavaScript DB, the image overflows; it doesn’t fit the device-width as the previous code does:
CSS:
<style type="text/css">
body {
padding:0;margin:0; background-color: #000;
}
.image-wrap{width:100%;}/* set min or max-widths as required*/
.image-wrap img{width:100%;height:auto;}
</style>
The code is very similar to this gist, which is an earlier version of the code attempting to use iScroll5: https://gist.github.com/StevenHu/0417e9e3bd73061687f0 (which I’m abandoning for this version on this SitePoint page, since I can’t get the pinch/zoom to work with a DB).
I was hoping it was a simple CSS issue, but I wonder if the CSS and image from the DB are not timed right to work with each other, like the image is being applied too late or too early for the CSS to work.
Yes it sounds more complex than a straight CSS issue especially as you say it works normally but not when injected.
Is the element width controlled by a media query at the point you inject it. I’m wondering whether the media query is failing and letting the width go back to the wrapper width - not that it helps us of course.
What happens if you hide the overflow on image-wrapper? Does the image wrapper stretch 1500px wide or is that working properly?
Perhaps you could trigger a redraw after the image has loaded. e.g. change a class on the body or something or maybe the redraw solution from here.
Unfortunately I think its one of those things you will have to throw code at until you can see a change.
What’s odd is that the CSS on the DB page has no effect at all. That is, I change the width of the img from 100% to 50% – even to 10% – and there was no difference in the image size.