Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to create a responsive table?

The tables may contain large data which cannot be filled up on a single screen especially on small devices. The rows data should be kept together to preserve its meaning. Responsive tables can adjust themselves with any type of screen size. In this tutorial, we will be creating responsive tables with CSS.

Creating a responsive table

We can add a horizontal scroll so that the contents of the table can horizontally scroll on small devices. To do so use overflow-x: auto property to the container class which will wrap the <table> tag.

Example: Creating a responsive table with CSS

Here, we have created a responsive table that adds horizontal scroll to the table.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>HTML </title>
</head>
<style>
    table, th, td{
      border: 1px solid black;
      border-collapse: collapse;	  
    }
	.container {
	   overflow-x: auto;
	}
	table {
	   width: 100%;
	}
  </style>
<body>
    <h2> Responsive Table </h2>
	<div class="container">
		<table>
		  <tr>
			<th> #</th>
			<th> Item 1 </th>
			<th> Item 2 </th>
			<th>Item 3</th>
			<th>Item 4</th>
			<th>Item 5</th>
			<th>Item 6</th>
			<th>Item 7</th>
			<th>Item 8</th>
		  </tr>
		  <tr>
			<th> cost </th>
			<td>500</td>
			<td>1000</td>
			<td>5000</td>
			<td>5000</td>
			<td>5000</td>
			<td>5000</td>
			<td>5000</td>
			<td>5000</td>
		  </tr>
		  <tr>
			<th> weight </th>
			<td>50</td>
			<td>60</td>
			<td>70</td>
			<td>70</td>
			<td>50</td>
			<td>50</td>
			<td>50</td>
			<td>50</td>
		  </tr>
		</table>
	</div>	
</body>
</html>

Output

Here is the output of the above code.

Responsive table

Example: Creating a responsive table using media Query rule

We can use the media Query rule to responsively set the table according to the size of the screen. Suppose in this example, we have defined media Query rule of screen size less than 500px, where we have used CSS to hide some columns.

Conclusion

In this tutorial, we have learned to create a responsive table with CSS. We have added overflow-x: auto to add horizontal scroll and media Query with some of the rule.



About the author: