kirypto kirypto - 5 months ago 8
CSS Question

How to make a html scrolling table inside a div with specific column sizes?

I am trying to make a table that allows scrolling both horizontally, but even though I specify the column width in the headers, it shrinks them down to the div size.

I want it to overflow to the right, and allow scrolling.

Here is a link to a jsfiddle test with something that acts like my current implementation, but here is a code snippet that runs the same code:



.mainframe {
overflow: hidden;
position: fixed;
background-color: blue;
height:200px;
width:500px;
}
.wrapper {
margin: 5%;
width: 90%;
height: 90%;
background-color: red;
}

.allow-scroll {
position: relative;
height: 100%;
width: 100%;
overflow-y: scroll;
overflow-x: scroll;
background-color: lime;
}

<div class="mainframe">
<div class="wrapper">
<div class="allow-scroll">
<table>
<tr>
<th style="width:200px">Long name item 1</th>
<th style="width:300px">Even longer name item 2</th>
<th style="width:400px">Super crazy long item 3 need more words</th>
<th style="width:200px">Short item 4</th>
<th style="width:300px">Somewhat long time 5</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
</div>
</div>
</div>





Additionally, could someone explain why the "margin 5%" doesn't work at the bottom, and what I could do about that?

Answer

You could add a width to the table so that it had horizontal scroll.

table {
    width:1400px;
}

A better option is to use the table-layoutproperty.

table {
    width:100%;
    table-layout:fixed;
}

The margin issue you are having is caused by the height on the .mainframe element.

Remove the height: 200px;

If you need the height on the .mainframe element and you know it will be a fixed height, you just need to decrease the height of the .wrapper element. You can use an exact pixel height. I used a percentage below.

.wrapper { height: 75%; } // This percentage looks about right.