John Smith John Smith - 7 months ago 13
HTML Question

Which is the best practices to create a responsive table?

I have this sample:

link

CODE HTML:

<table class="table table-striped">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone</td>
<td>Adresss</td>
<td>Message</td>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Smith</td>
<td>jhs@yahoo.com</td>
<td>0766323123</td>
<td>Test</td>
<td>Test</td>
</tr>
<tr>
<td>Ronny</td>
<td>Stuard</td>
<td>ros@yahoo.com</td>
<td>0877223534</td>
<td>Test2</td>
<td>Test2</td>
</tr>
</tbody>
</table>


I found this example and want to do something like

sample responsive table

What I do not understand is how CSS code is written.
I need a short sample code CSS to turn my table to be like over there.Also if you know better examples to make a table responsive please put here

After all that is the best way to make a table responsive?

Thanks in advance!

Answer

Use this code of css for your table:

@media
only screen and (max-width: 500px),
(min-device-width: 500px) and (max-device-width: 500px)  {

    /* Force table to not be like tables anymore */
    table, thead, tbody, th, td, tr {
        display: block;
    }

    /* Hide table headers (but not display: none;, for accessibility) */
    thead tr {
        position: absolute;
        top: -9999px;
        left: -9999px;
    }

    tr { border: 1px solid #ccc; }

    td {
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee;
        position: relative;
        padding-left: 50%;
    }

    td:before {
        /* Now like a table header */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%;
        padding-right: 10px;
        white-space: nowrap;
    }

    /*
    Label the data
    */
    td:nth-of-type(1):before { content: "First Name";
        text-align: left;
        font-size: 12px;
    }
    td:nth-of-type(2):before { content: "Last Name";
        text-align: left;
        font-size: 12px;
    }
    td:nth-of-type(2):before { content: "Email";
        text-align: left;
        font-size: 12px;
    }
    td:nth-of-type(2):before { content: "Phone";
        text-align: left;
        font-size: 12px;
    }
    td:nth-of-type(2):before { content: "Address";
        text-align: left;
        font-size: 12px;
    }
    td:nth-of-type(2):before { content: "Message";
        text-align: left;
        font-size: 12px;
    }
}

@media (max-width: 500px)
{
    td
    {
        font-size: 12px!important;
        text-align: right!important;
        padding-right: 5px;
    }
}

Add the size of the screen as you want the table to be converted in responsive like the example you gave. In this case is for 500px and less.

Comments