Search code examples
htmlcssoverlayfluid-layoutaspect-ratio

Centered fluid image with fixed aspect ratio and cropping - 2 overlayed divs


I'm trying to use CSS only and no JavaScript, although that would not be a problem.

Requirements: A horizontally centered image with a fixed aspect ratio (3:2). The image itself does not have a 3:2 aspect ratio, it's taller, so the bottom should be cropped. The image should be fluid, always scaling with the window, both in portrait and landscape orientations. It has a maximum width and height, so as to always be visible on screen.

I have managed to do all this, although it doesn't seem an elegant solution: it needs a transparent png to force the aspect ratio, and uses background-image to show the image itself. See here: http://jsfiddle.net/fseixas/u4e4xx1f

Now I need to have another div overlayed on top of this one, and I'm not able to do it. Any help?

(also, if you can provide a more elegant solution to the image problem, please do!)

Thanks,
fseixas


Solution

  • I've altered your Fiddle so that no image is needed. I've changed almost all the code, but what I've basically done, is add a container that will always have the perfect width of max-width: calc(100vw - 60px) and a width of calc(150vh - 180px) (1.5 times what the max-height should be and accounting for the header, footer and the margins).

    Then I gave #imagem a padding-bottom of calc(100% / 1.5), meaning that it will get exactly the same height as width, but divided by 1.5 (resulting in a ratio of 2:3.

    Hope this solved your problem