0

How to add a horizontal scrollbar to a html table so as to show the scrollbar only on mobiles but not wider screens. I tried what is mentioned at, "https://stackoverflow.com/questions/5533636/add-a-horizontal-scrollbar-to-an-html-table"

HTML

<div class="table_wrapper">
<table......>
......
</table>
</div>

CSS

<style> 
 .table_wrapper{
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}
</style>
Ramaanand
  • 27
  • 6

1 Answers1

2

I threw together a little demo that hopefully solves your problem.

To get the table to function as a block, and allow scroll bars and hold it's own width instead of fit the width of it's content we first set display: block

Now that the table will hold it's own width we want to make sure it tries to make the width perfect for the content, se we set width: max-content

However, I'm assuming we don't want it to get too big. Now we need to add a limit, you're probably wanting it to be filling the container if you're using a wrapper so maybe 100% would be best for you, however for my purposes I set max-width: 80% so even if the content is too large on mobile, it will only make the width up to 80% of it's container.

Now we need to decide what happens when we have overflowing content, or the child is too big for the parent, I set overflow: auto which will just automatically set the scroll bars when overflowing, and not when there is no overflow.

to force a width on the row without content I set it to a block as well, and I also made it possible to resize the table so that you could emulate the screen getting smaller without needing to use any dev tools. There are some decorative borders on mine and such to make it more clear in the demo where elements are.

Let me know if you have any problems or questions with my example!

table {
  display: block;
  width: max-content;
  max-width: 80%;
  overflow: auto;
  
  resize: horizontal;
  border: 1px solid black;
}
tr {
  display: block;
  border: 1px solid red;
  width: 200px;
  height: 20px;
}
<table>
  <tr></tr>
  <tr></tr>
  <tr></tr>
</table>
async await
  • 1,967
  • 1
  • 8
  • 19
  • Having the table displayed as a block to include a scrollbar will break much functionality of a table for screen readers and accessibility devices. I would recommend using a wrapper on your table that scrolls instead, unless you have familiarity with aria-labels and testing with accessibility devices. – async await Sep 02 '23 at 00:07
  • It is working perfectly. Thank you very much! – Ramaanand Sep 02 '23 at 04:37