'How do I make a table scrollable
Does anyone know a vanilla way of making the body of a table scrollable using only html and css?
The obvious solution
tbody {
height: 200px;
overflow-y: scroll;
}
does not work.
Wouldnt this be the obvious use of tables?
am I doing something wrong?
Solution 1:[1]
You need to declare a height first, else your table will expand to the according width of its content.
table{
overflow-y:scroll;
height:100px;
display:block;
}
EDIT: after clarifying your problem I edited the fiddle: check out this Example or that way. It's rather hacky and not guaranteed to work crossbrowser but might work for your case.
Solution 2:[2]
You can't do that with a table. Wrap the table with a div a give it something like:
div.wrapper {
overflow:hidden;
overflow-y: scroll;
height: 100px; // change this to desired height
}
Solution 3:[3]
You can wrap the table with a parent div
and make him scrollable as scoota269 advised:
.div_before_table {
overflow:hidden;
overflow-y: scroll;
height: 500px;
}
And to keep the table header sticky you can add a fixed
class:
.th.fixed {
top: 0;
z-index: 2;
position: sticky;
background-color: white;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #ddd;
}
/* The scrollable part */
.scrollable {
height: 150px;
overflow-y: scroll;
border-bottom: 1px solid #ddd;
}
th {
position: sticky;
background-color: white;
z-index: 2;
top: 0;
}
<div class="scrollable">
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</div>
Solution 4:[4]
Do you want somthing like this ?
Pure CSS Scrollable Table with Fixed Header (1)
http://anaturb.net/csstips/sheader.htm
http://www.scientificpsychic.com/blogentries/html-and-css-scrolling-table-with-fixed-heading.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jessica Tiberio |
Solution 2 | scoota269 |
Solution 3 | David Bendahan |
Solution 4 |