Reputation: 5395
There is a page-wide image (width=100%
) on a mobile web page. When the page is loaded, the items below the image are displayed for a moment directly after the items above it, as if the image is not there - until the image is loaded - and then they are shifted down to their normal place. Can I somehow get rid of that flashing?
The problem is that different mobile devices have different screen width, so it is not possible to set the image height in advance. The aspect ratio of the images is known, but this does not seem to help.
To clarify, the code I have is:
<meta name="viewport" content="width=device-width, initial-scale=1.0, scrollbar=no"/>
...
<div class="image-container">
<img src="..."/>
</div>
<div>
Text after the image
</div>
CSS:
.image-container {
width: 100%;
}
.image-container img {
width: 100%;
}
If you try to run the fiddle http://jsfiddle.net/ocL7wf9j/ , you will see that until the image loads, the text below it is displayed on top of the page (which can be expected, because the browser does not the image dimensions before it gets the image file) - I want it to be displayed in its proper place from the very beginning. The dimensions of the image are known to me (e. g. they are 640x229 for the example image in the fiddle), but how can I get it to work with all screen widths?
Upvotes: 1
Views: 1049
Reputation: 302
You can add some JavaScript to change the height of <div class="image-container">
whenever the page loads or whenever the window resizes. I recommend using JQuery (a JavaScript library) to do so.
var aspectratio = 2.8;
var image = $('.image-container');
$(window).on('resize', function () {
var width = $('.image-container').width();
image.height(width / aspectratio);
}).trigger('resize'); //on page load
Here is a working JSFiddle: https://jsfiddle.net/ocL7wf9j/11/
You can include JQuery on your website for free from Google.
<script type="text/javascript">
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
</script>
Upvotes: 1