[HTML] <table> 태그의 Body영역에서 스크롤바 사용하기
수 백 건의 레코드를 가진 TABLE의 데이터를 보려면 브라우저의 수직 스크롤바를 사용해서 이동해야 했습니다. 그래서 생각해봤죠! 헤더를 고정하고 테이블 바디만 스크롤하면 되지 않을까? 누군가는 반드시 저와 같은 생각을 하고 있을꺼라고. 그래서 구글링을 했습니다. 있었습니다.
먼저 아래와 같이 CSS를 등록합니다. display 속성을 이용해서 테이블 바디를 스크롤할 수 있게 설정하는 방법입니다.
<style> .fixed_header { width: 400px; table-layout: fixed; border-collapse: collapse; } .fixed_header tbody { display: block; width: 100%; overflow: auto; height: 100px; } .fixed_header thead tr { display: block; } .fixed_header thead { background: black; color: #fff; } .fixed_header th, .fixed_header td { padding: 5px; text-align: left; width: 200px; } </style>
다음으로 테이블 영역을 만듭니다. TABLE 태그의 class 속성에 “fixed_header”를 지정합니다.
<table class="fixed_header">
<thead>
<tr>
<th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td>
</tr>
<tr>
<td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>11</td><td>12</td><td>13</td><td>14</td><td>15</td>
</tr>
<tr>
<td>16</td><td>17</td><td>18</td><td>19</td><td>20</td>
</tr>
<tr>
<td>21</td><td>22</td><td>23</td><td>24</td><td>25</td>
</tr>
<tr>
<td>26</td><td>27</td><td>28</td><td>29</td><td>30</td>
</tr>
</tbody>
</table>
아래와 같은 결과를 얻을 수 있습니다. 테이블 헤더를 고정하고 테이블 바디만 스크롤헤서 데이터를 확인할 수 있습니다.
Col 1 | Col 2 | Col 3 | Col 4 | Col 5 |
---|---|---|---|---|
1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 |
출처: How to Create a Table with a Fixed Header and Scrollable Body