Scrolling through the contents of a table

Scrolling through the contents of a table

To make a table with a fixed height and vertical scrolling, you need to split it into two parts.

The first will contain the table header, the second will contain the body in a container with the overflow-x: auto property.

<div class="scroll-table">
	<table>
		<thead>
			<tr>
				<th>Name of the dish</th>
				<th>Protein</th>
				<th>Fats</th>
				<th>Carbohydrates</th>
				<th>Kcal</th>
			</tr>
		</thead>
	</table>	
	<div class="scroll-table-body">
		<table>
			<tbody>
				<tr>
					<td>Azu</td>
					<td>11,9</td>
					<td>14,2</td>
					<td>10,2</td>
					<td>214</td>
				</tr>
				...
			</tbody>
		</table>
	</div>	
</div>
HTML

CSS styles:

.scroll-table-body {
	height: 300px;
	overflow-x: auto;
	margin-top: 0px;
	margin-bottom: 20px;
	border-bottom: 1px solid #eee;
}
.scroll-table table {
	width:100%;
	table-layout: fixed;
	border: none;
}
.scroll-table thead th {
	font-weight: bold;
	text-align: left;
	border: none;
	padding: 10px 15px;
	background: #d8d8d8;
	font-size: 14px;
	border-left: 1px solid #ddd;
	border-right: 1px solid #ddd;
}
.scroll-table tbody td {
	text-align: left;
	border-left: 1px solid #ddd;
	border-right: 1px solid #ddd;
	padding: 10px 15px;
	font-size: 14px;
	vertical-align: top;
}
.scroll-table tbody tr:nth-child(even){
	background: #f3f3f3;
}

/* Scroll styles */
::-webkit-scrollbar {
	width: 6px;
} 
::-webkit-scrollbar-track {
	box-shadow: inset 0 0 6px rgba(0,0,0,0.3); 
} 
::-webkit-scrollbar-thumb {
	box-shadow: inset 0 0 6px rgba(0,0,0,0.3); 
}
CSS

Result:

17.12.2020, updated 16.03.2021
252

Comments

to add a comment.

Other publications

Heading with a horizontal line in the middle
One way to make a heading with a horizontal line in the center without an image (background-image).
53
0
The viewport meta tag
Initially, the viewport meta tag appeared in the mobile version of Safari, then it was picked up by other developers and mobile browsers, although it is not part of the W3C standard.
34
0
Styling Checkbox
Here are some examples of how to change the look of checkboxes using CSS, images and some JS.
174
0
Smooth background change
This effect can be easily done through the CSS transition property for example buttons, menus, etc.
148
0
Connecting fonts in CSS
If you do not delve into the details, you can quickly connect the font like this ...
82
0
Aligning a block to the center of its parent
Examples of how to position an element in the center of its parent using absolute, flexbox and grid layout.
86
0