Recently I dealt with an interesting challenge with how to create a layout for a particular scenario. I had a webpage that displayed products in tiles. I needed the tiles of a certain width but needed the tiles to automatically wrap to the next line based on screen width. The tiles also needed to have the same height as the tallest tile in that row.
The page was originally setup using a ul as the parent container and then the li elements to actually hold the tile data. The li elements floated left to have a fluid grid. This was fine when the page was originally created because there was a specified height. So all tiles had the same height. This was fine before they decided to change the requirements to have the height be dynamic based on the content that filled the tiles.
So with wanting a pure CSS solution, I started experimenting with different solutions. I couldn’t use the display:table method because that requires you to create separate rows. Since I needed it to be fluid this would not work. My next thought was to try using display:inline-block. This allowed me to have the fluid amount of tiles in each row, but the heights were all just based on the content in the individual tiles. I looked awhile and could not find a way to get the height to adjust to the tallest tile in the row.
I wasn’t ready to give up. My friend suggested I look at the flexbox model. I started looking it up but it seemed like it only adjusted width. Again this is not what I needed so I continued my search on google. I finally game across a blog post titled Floats, Inline Block or Display Table? Or Flexbox? This seemed promising since these were all the methods I had tried to use. I figured I would read the blog post and see if there was something I missed. This blog post was very helpful. It compared all these methods and clearly spelled out the advantages and disadvantages of each method. My joy came when I was reading the advantages of Flexbox section and saw this: “- Equal heights”. This was exactly what I was needed.
So after reading that I went back to documentation on Flexbox since I had never used it. I used the examples to construct a test of my own on codepen. At first it didn’t seem to work. The tiles were just in a vertical line. After more digging it seemed that safari had to have the -webkit prefix in the value of the display. So instead of:
display:flex I needed to use
display: -webkit-flex. This did the trick and worked exactly like I needed.
I was super excited to have found a solution for this problem and am intrigued by the possibilities presented with flexbox. I saved my solution on codepen so I could share it with anyone else that needed something similar. You can view it on my pen titled Flexbox Fluid Rows with Dynamic Height.