Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active August 29, 2017 09:28
Show Gist options
  • Save OliverJAsh/adfd1b8cf8bd2e0f4578ac4c20528d52 to your computer and use it in GitHub Desktop.
Save OliverJAsh/adfd1b8cf8bd2e0f4578ac4c20528d52 to your computer and use it in GitHub Desktop.
Unsplash image layout

Solution: http://jsbin.com/melewe/3/edit?html,css,js,output

The requirements are:

  1. Reserve space for the image whilst it loads.
  2. Contain image (including padding) in viewport (fill width or height, whichever is smallest), whilst only taking up necessary space.
  3. Minimum height
  4. Responsive images

For 1 we can use the padding-bottom trick.

Because all elements are constrained on the X axis by default, we have to express constraints along the Y axis as constraints along the X axis. For 2 we have to define the maximum height as a max-width (calculated using vh units and the aspect ratio). For 3 we have to define the minimum height as a min-width (calculated using the aspect ratio).

For 4 we want to repeat the layout described in 2 and 3 for the img sizes attribute. My current solution requires JavaScript due to the lack of calc in media queries (https://bugs.chromium.org/p/chromium/issues/detail?id=421909), which unfortunately means we lose benefits of the preloader, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment