Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image with declared width and height renders square before load

Tags:

html

css

image

I have images with declared widths and heights, e.g.:

<img src="foo.jpg" width="1500" height="1800" alt="bar" />

They are within a responsive grid, so they display at max-width: 100%. They are lazyloaded in. The problem is that despite having height: auto;, the images always display square before they are loaded, which creates a jump in page height when they have finished loading.

So the above image example, in my 960px width grid, would display a placeholder at 960px x 960px until the full image loads, at which point it will be 960px x Y (where Y is the correct height).

My question is how can I get the placeholder image to mimic the final loaded dimensions of the actual image?

like image 602
cavill Avatar asked Oct 26 '13 12:10

cavill


People also ask

What is lazy loading image?

Lazy Loading images is a technique to load images on a web page only when required. This way can improve the page's loading time without reducing the page size. Users can only view its first fold and associated images when they open a website. The images below the first fold need not be loaded right at the beginning.

How do you maintain the aspect ratio of an image?

By setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained. The end result is an image that scales up or down perfectly.

How do I force an image to size in HTML?

One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.


1 Answers

The following is the only solution that worked 100% of the time, and is much simpler: https://css-tricks.com/preventing-content-reflow-from-lazy-loaded-images/

In short you can use an SVG placeholder image that contains the dimenions:

<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 3 2'%3E%3C/svg%3E" data-src="//picsum.photos/900/600" alt="Lazy loading test image" />

Here is an React example:

const placeholderSrc = (width, height) => `data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"%3E%3C/svg%3E`

const lazyImage = ({url, width, height, alt}) => {
  return (
    <img
      src={placeholderSrc(width, height)}
      data-src={url}
      alt={alt} />
  )
}
like image 161
IT-Dan Avatar answered Nov 16 '22 01:11

IT-Dan