A coding challenge that I faced today consisted of responsive table cells that needed to maintain equal height and width dimensions at every screen size. I wanted table cell that looked like perfect squares for building an online calendar. I didn’t want to use any Javascript to dictate the cell height, so after a few hours I came up with a CSS-only approach that works pretty well! The best thing about my solution…it’s basically just one line of code!
Disclaimer: It works “pretty” well… I wanted to form perfect squares, but the solution is not technically “pixel-perfect” at all screen sizes. But don’t let that scare you away…read on! I think you’ll like the outcome.
You need to start with an HTML table that looks something like this:
https://gist.github.com/danbru1989/03abdb678b48e1bdacfd0053b5e91e35
Then you’ll want to add this CSS code to cause the table to maintain equal dimensions both vertically and horizontally at all times:
https://gist.github.com/danbru1989/5d2647b7e6a6b68d7d091c25a7bf45ea
The key is in the use of the vw CSS unit. W3 defines this as, “Relative to 1% of the width of the viewport”. The viewport is your browser window size. Using vw’s enables you to set the height of an element to be relative to the width of the browser window. A simple solution and browser support is great too – just how we like it!
My Application
I was attempting to style the default calendar for the powerful Events Manager plugin. Making the calendar responsive horizontally is quite easy enough, but the vertical cell height threw me for a loop until I came up with this.
Please comment below if you have any improvements for my solution or if you have any questions about how to make the default Events Manager calendar fully responsive. I’d be glad to hear from you!
Good to know about vw! It didn’t work quite right when I did it on the tr, but doing it for my td’s worked perfect!
Glad it helped you out! Tr may not work all the time depending on your situation. You did the right thing and tried it on the td instead.