I've been falling in love with CSS grid and aspect-ratio as I've been building Good Gear Club over the past month or so but I still have a scenario that has me stumped.
Below is the basic layout of 8 boxes with two of them at a larger size to highlight them. Every 'regular' box is a grid item that is sized using the aspect-ratio property and over on Good Gear Club, I'm using the object-fit property to size images rather than reverting to background images which is the technique I've used to overcome sizing and placement issues in the past.
The two boxes are sized slightly differently, for the largest it already has an aspect-ratio set so I only need to dictate the size. By setting the 'grid-column' and 'grid-row' properties to 'span 2', the item will grow to fill two rows and two columns. Despite using aspect ratio, if I only set the column property, the row introduces a bunch of space which you can see by clicking on the 'toggle grid-row' button in the pen above.
Overall, the aspect-ratio approach does work really well. If I kept everything square there would be no problems but of course I decided that there should be cases where something is two columns wide but only a single row in height. The solution seems obvious, instead of being a 1 / 1 ratio where everything is equal it should become 2 / 1 so everything is twice as wide as it is high.
But I've made use of the 'gap' property. This introduces a bit of complexity because the aspect ratio actually needs to be 2 (+gap) / 1.
This is what it looks like if we set the aspect ratio to 2 / 1:
The sixth item is slightly taller than the other items in the row. I've overcome it by setting the value to 4 / 1.95 which I got to with some experimentation but that was pure fluke. If I set the same value for this example it's not really much better so for this smaller example the value that works is 4 / 1.525.
I don't know how this should be solved, but it does feel like an oversize in the spec for aspect-ratio. Anything other than a square doesn't really work and I would love it to calculate what it needs to do all by itself.
|More from 1 Thing A Week|
|« A look back at my 2022||My New Year's Resolutions for 2022||Why the order property in CSS frustrates me »|
You can find 1 Thing A Week on Twitter, Facebook, Instagram & Reddit