Use CSS to make the table responsive

A practical way to make the form beautifully displayed on the mobile phone

A few days ago, I received a warningGoogle Search Console. It detects mobile usability issues on a page where I have a large table.

This is the table that gave me the problem:

On mobile devices, it renders poorly:

Bad user experience, and errors in Google Search Console. If there is something I don't want, it is an error/warning. It won't work when I can solve it.

Hugo, the static website generator I use, just add one<style>Mark it in the markdown file. convenient.

Therefore, I started looking for a good way to make the watch responsive. I saw this very good article on CSS Tricks:Response data sheet. Since 2011, it can still be used normally!

The trick is this: we want the table to be displayed as a block element, not a table in the traditional CSS sense. We hide all table headers by moving all table headers out of view, and insert a new block in the table, each row will have its own set of table headers, as shown below:

This is the code that implements the above design:

@media
only screen and (max-width: 1500px) {
  table, thead, tbody, th, td, tr {
    display: block;
  }
  thead tr {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  tr { border: 1px solid #ccc; }
  td {
    border: none;
    border-bottom: 1px solid #eee;
    position: relative;
    padding-left: 200px;
    margin-left: 150px;
  }
  td:before {
    position: absolute;
    top: 12px;
    left: 6px;
    width: 200px;
    padding-right: 40px;
    white-space: nowrap;
    margin-left: -150px;
  }
  td:nth-of-type(1):before { content: "Option"; }
  td:nth-of-type(2):before { content: "Description"; }
  td:nth-of-type(3):before { content: "Type"; }
  td:nth-of-type(4):before { content: "Default";}
}

The important thing you need to customize to make your own table responsive is the last 4 rows-you need to enter the title of each "column", and if you have more columns, you need to add more. Or, if the number is small, delete it.

The other thing is that the new "title" will take up space in each row. I added one150pxMargin, you need to quote 2 times: once formargin-left: 150pxinsidetdAnd asmargin-left: -150pxinsidetd: before.

Finally, you need to determine when to start the new layout. When the page is smaller than 1500px, I activate it because the table is large. I can also set it as the default behavior instead of displaying a normal table on a big screen, but so far, I think the problem has been solved.

I hope this helps.

Download mine for freeCSS Manual


More CSS tutorials: