04 May 2016

Height equals dynamic width (CSS fluid layout)

On the DJ Vadim website I needed to create a gallery of album covers that displayed each cover in a perfect square, but was also responsive and would resize dynamically on various screen sizes. I could have declared a whole variety of CSS values for each media breakpoint, but I wanted a much more elegant solution. I settled on the following:

Check the J Fiddle

The solution is to give the containing hyperlink for each thumbnail a width off 100%, and a height of 0. The square is calculated by a bottom padding of 100%. The image itself is applied as a background image to the hyperlink, and sized using the CSS property background-size.

While the above method works for containers that only hold a background image, as soon as content is put inside the container the height breaks (adding the height of the content to the dimensions of the container) and a perfect square is lost.

Here is another solution using flex box that can also perfectly center content within the container (Does not work correctly in Safari)

Taking it a step further, the following snippet creates a more repsonsive layout. Adjust the width for teh flex-items using media queries.


Another update:
Who knew this could be so hard. Here's the latest crossbrowser solution