3 ms·
Ask HN: 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:
<div class="hidden md:block large">
{{ template "_table_large" . }}
</div>
<div class="md:hidden small">
{{ template "_table_small" . }}
</div>
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.
- andrewfromx 3y agoBig Table logic: {{ $headers := index . "headers" }} {{ range $i, $h := $headers }} <th>{{ $h }}</th> {{ end }} {{ $cells := index . "cells" }} {{ range $i, $c := $cells }} <tr> {{ range $j, $cell := $c }} <td> {{ $cell }} </td> {{ end }} </tr> {{ end }}
- andrewfromx 3y agoSmall Table logic: {{ $cells := index . "cells" }} {{ $headers := index . "headers" }} {{ range $j, $c := $cells }} {{ range $i, $h := $headers }} <tr> <th>{{ $h }}</th> <td>{{ index $c $i}}</td> </tr> {{ end }} {{ end }}
- uzername 3y agoI 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 https://developer.mozilla.org/en-US/docs/Web/CSS/attr