html - CSS to display table row headers above data cells -
suppose have table on html page, purple border around th
cells , green border around td
cells:
some code produces (the css view-small
class isn't in use in above display it's explained):
<meta http-equiv="x-ua-compatible" content="ie=edge"> <title>table transformation</title> <link href='https://fonts.googleapis.com/css?family=open+sans:400,400italic,700,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=open+sans+condensed:300,300italic,700' rel='stylesheet' type='text/css'> <style> body { font-family: "opens sans", sans-serif; } td { border: 1px solid green; } th { border: 1px solid purple; } .view-small table { display: block; width: 100%; } .view-small tbody { display: block; } .view-small tr { display: block; width: 100%; margin: 2em auto; position; relative; } .view-small th { display: block; width: 100%; position: absolute; left: 50%; transform: translatex(-50%); } .view-small td { display: inline-block; height: 1em; width: 30%; transform: translatey(1.5em); } </style> <body class=""> <h1>table example</h1> <table> <tr> <th>numbers</th> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <th>countries</th> <td>canada</td> <td>mexico</td> <td>guatemala</td> </tr> <tr> <th>planets</th> <td>mars</td> <td>jupiter</td> <td>saturn</td> </tr> </table> <p>end of test</p> </body>
we thinking smaller devices, neat if save horizontal space display each row header on corresponding data cells. if set class="view-small"
in body tag in code above, in chrome on windows , pretty same thing in firefox , ie11:
this demonstrates i'm going for. i'd achieve includes having data cells take horizontal space full row have occupied. in above code, have width set artificially 30%, isn't ideal!
i'm going tinker more, thought i'd see whether else has tried or seen solution somewhere!
use box-sizing:border-box
box model.
then can use calc()
width
applying ((100% / 3) - 3px) , divides 100% of screen 3 boxes subtract 3px
border
each px
each box, because yo using box-sizing
*, *::before, *::after { box-sizing: border-box } body { font-family: "opens sans", sans-serif; margin: 0 } td { border: 1px solid green; } th { border: 1px solid purple; } .view-small table { display: block; width: 100%; } .view-small tbody { display: block; } .view-small tr { display: block; width: 100%; margin: 2em auto; position: relative; } .view-small th { display: block; width: 100%; position: absolute; left: 50%; transform: translatex(-50%); } .view-small td { display: inline-block; width: calc((100% / 3) - 3px); transform: translatey(1.5em); }
<body class="view-small"> <h1>table example</h1> <table> <tr> <th>numbers</th> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <th>countries</th> <td>canada</td> <td>mexico</td> <td>guatemala</td> </tr> <tr> <th>planets</th> <td>mars</td> <td>jupiter</td> <td>saturn</td> </tr> </table> <p>end of test</p> </body>