HTML 테이블은 데이터를 행(row)과 열(column)로 정리하여 표시할 때 사용된다. 특히 구조화된 정보나 데이터 목록을 제공할 때 사용된다.
1. 기본 구조
HTML에서 테이블은 <table> 태그로 생성한다.
기본 테이블 구조
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</tbody>
</table>
- <table>: 테이블의 루트 태그.
- <thead>: 테이블 헤더 영역.
- <tbody>: 테이블 본문 영역.
- <tr>: 행(Row)을 정의.
- <th>: 헤더 셀(Header Cell)을 정의 (기본적으로 굵은 글씨, 가운데 정렬).
- <td>: 데이터 셀(Data Cell)을 정의 (기본적으로 왼쪽 정렬).
2. 고급 테이블 태그
2.1. <tfoot>
- 테이블의 마지막 부분에 위치하며, 합계나 요약 데이터를 표시할 때 유용.
<tfoot>
<tr>
<td colspan="2">Total</td>
<td>100</td>
</tr>
</tfoot>
2.2. 셀 병합
- 행 병합 (rowspan): 하나의 셀이 여러 행에 걸쳐 확장.
- 열 병합 (colspan): 하나의 셀이 여러 열에 걸쳐 확장.
<table>
<tr>
<th rowspan="2">Row Header</th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td colspan="2">Merged Column</td>
</tr>
</table>
3. 스타일링 테이블
3.1. 기본 스타일링
- 테이블에 기본 테두리 및 셀 간격 추가.
<style>
table {
border-collapse: collapse; /* 중복 테두리 제거 */
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2; /* 헤더 배경색 */
}
</style>
3.2. Zebra Stripes (대각선 줄무늬 효과)
- CSS를 이용해 행마다 다른 배경색을 추가해 가독성을 높임.
<style>
tbody tr:nth-child(odd) {
background-color: #f9f9f9;
}
tbody tr:nth-child(even) {
background-color: #e0e0e0;
}
</style>
4. 접근성과 활용
4.1. 캡션 추가
- 테이블의 제목을 제공.
<table>
<caption>Monthly Sales Data</caption>
<!-- Table content here -->
</table>
4.2. 스크린 리더 지원
- scope 속성: 헤더 셀의 범위를 명시.
- scope="col": 열에 적용.
- scope="row": 행에 적용.
- aria-label이나 aria-describedby: 접근성 설명 추가.
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">Alice</td>
<td>30</td>
</tr>
</tbody>
</table>
6. 동적 테이블 (JavaScript 활용)
6.1. 행 추가/삭제
<script>
function addRow() {
const table = document.getElementById('myTable');
const newRow = table.insertRow();
const cell1 = newRow.insertCell(0);
const cell2 = newRow.insertCell(1);
cell1.innerHTML = 'New Data 1';
cell2.innerHTML = 'New Data 2';
}
</script>
<button onclick="addRow()">Add Row</button>
<table id="myTable">
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
6.2. 데이터 정렬
- JavaScript로 특정 열을 기준으로 테이블 데이터를 정렬.
<script>
function sortTable(columnIndex) {
const table = document.getElementById('myTable');
const rows = Array.from(table.rows).slice(1); // 헤더 제외
rows.sort((a, b) => a.cells[columnIndex].innerText.localeCompare(b.cells[columnIndex].innerText));
rows.forEach(row => table.appendChild(row)); // 재정렬
}
</script>
<button onclick="sortTable(0)">Sort by Column 1</button>
<table id="myTable">
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Banana</td>
<td>3</td>
</tr>
<tr>
<td>Apple</td>
<td>2</td>
</tr>
</table>
'HTML' 카테고리의 다른 글
Forms and Validations (0) | 2024.12.30 |
---|---|
시멘틱 코드 (1) | 2024.12.30 |
HTML5 캔버스 및 SVG (0) | 2024.12.30 |
링크와 미디어 삽입 (1) | 2024.12.27 |
요소 (1) | 2024.12.26 |