HACKER Q&A
📣 andrewfromx

How do you display HTML tables on any screen size?


For the longest time I hated how I could not easily make HTML tables that are showing nice excel like data (i.e. they are really correctly using table, tr, and td tags for data not layout) to look good on mobile.

I finally have a solution I love. I keep using it over and over.

headers := []string{"name", "age", "species", "home_planet", "language", "occupation"}

I define the headers and call:

c.MakeCells(list, headers, "_welcome")

The list is an array of key values pairs, and _welcome is just the name of the view.

{{ define "_welcome_col1" }} {{ $row := index . "row" }} {{ index $row "name" }} {{ end }}

{{ define "_welcome_col2" }} {{ $row := index . "row" }} {{ index $row "age" }} {{ end }}

etc.

Then with tailwindcss I have:

{{ template "_table_small" . }}

So I'm rendering both the tables on the page but only 1 will show depending on the size of the screen.

And the logic in _table_small is the secret to the whole thing. Instead of displaying each row horizontally, it repeats the headers vertically as col1 and then col2 is each row value.

You can see demo at https://many.pw/

Just make the window smaller if you are on desktop and it will jump to the small version.


  👤 uzername Accepted Answer ✓
I recently saw a cool trick with css and tables. Using after pseudo selector with content and the attr css function, the small viewport layout showed the th labels without having to have two simultaneous tables in the dom. I think the downside of this could be accessibility issues, since I'm not sure if a screen reader would see those virtual labels vs literally reading what's in dom.

https://developer.mozilla.org/en-US/docs/Web/CSS/attr


👤 andrewfromx
Big Table logic:

                {{ $headers := index . "headers" }}
                {{ range $i, $h := $headers }}
                {{ $h }}
                {{ end }}

                {{ $cells := index . "cells" }}
                {{ range $i, $c := $cells }}
              
                {{ range $j, $cell := $c }}
                
                    {{ $cell }}
                
                {{ end }}
              
              {{ end }}

👤 andrewfromx
Small Table logic:

                {{ $cells := index . "cells" }}
                {{ $headers := index . "headers" }}
                {{ range $j, $c := $cells }}

                {{ range $i, $h := $headers }}
              
                {{ $h }}
                {{ index $c $i}}
              
              {{ end }}
              {{ end }}