With the growing use of websites on Mobile screens, the need for solving issues related to the responsiveness of HTML components has increased. One such component is the HTML table.

Generally, HTML tables do not break UI in case of desktop but because the screen size of mobile devices are small, and if you have a table which has more than 4-5 columns then most likely the table will extend out of the UI and you will see a horizontal scroll bar, which is not very good as far as user experience is concerned.
There are two ways to solve this:
-
By creating a container to keep the table.
-
Making the table horizontally scrollable.
Keep the table inside a div Container:
We can enclose the table in a <div> tag and provide the following styling to the <div> tag:
.table-container {
width: 100% !important;
overflow-x: scroll;
}
To make it even better, we can even set a width for column tables:
th, td { min-width: 200px; }
It is not necessary to have this style for evry screen size and you can only add this for screen size smaller than say 556px or more, using the @media query in CSS.
@media (max-width: 600px) {
.table-container {
width: 100% !important;
overflow-x: scroll;
}
th, td {min-width: 200px; }
}
|
Also Read: Learn HTML |
Making the table horizontally scrollable:
This is a better solution and we have implemented this in our website too. With this solution you do not have to enclose the table inside any other tag, as this style rule is applied directly on the table tag.
table {
display: block;
max-width: -moz-fit-content;
max-width: fit-content;
margin: 0 auto;
overflow-x: auto;
white-space: nowrap;
}
Just like we used the @media query above, for this CSS styling too, we can use the @media query to apply these CSS style rules only for small screen sizes.
@media (max-width: 600px) {
table {
display: block;
max-width: -moz-fit-content;
max-width: fit-content;
margin: 0 auto;
overflow-x: auto;
white-space: nowrap;
}
}
Conclusion:
Hope these two solutions help you in making your HTML table responsive and improve the user experience on your website. If you face any issue, please do share it with us in the comment section below.
You may also like:



