HTML
table 태그를 의미론적으로 제대로 쓰는 방법
Socratone
2021. 5. 1. 16:52
표 형태로 데이터를 보여줄 때에는 <table>을 써야 한다.
<tr>은 테이블의 한 열을 의미하고 <th>와 <td>는 각 열의 한 칸씩을 차지한다.
<th>에는 테이블의 제목이 들어가고 <td>에는 데이터가 들어간다.
<table>
<tr>
<th>제목 1</th>
<th>제목 2</th>
</tr>
<tr>
<td>데이터 1</td>
<td>데이터 2</td>
</tr>
</table>
colspan 속성을 넣어서 <th>나 <td>가 두 칸을 차지하게 할 수도 있다.
<table>
<tr>
<th colspan="2">제목</th>
</tr>
<tr>
<td>데이터 1</td>
<td>데이터 2</td>
</tr>
</table>
위의 태그들만 사용하더라도 표를 그리는 데에는 문제가 없지만 검색 엔진이 표의 제목이 무엇인지 내용이 무엇인지 등을 알 수 있게 하려면 <thead>, <tbody>, <tfoot>도 넣어줘야 한다.
<table>
<thead>
<tr>
<th>제목 1</th>
<th>제목 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>데이터 1</td>
<td>데이터 2</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>foot 1</th>
<th>foot 2</th>
</tr>
</tfoot>
</table>
CSS
<table>, <th>, <td> 모두에 border를 설정하면 테이블 라인이 두 줄로 나타난다.
이를 하나로 묶어주려면 border-collapse: collapse;를 넣어준다.
table,
th,
td {
border: 1px solid grey;
border-collapse: collapse;
padding: 10px;
}
예제

아래 코드를 넣으면 위와 같은 표를 만들 수 있다.
<table>
<thead>
<tr>
<th colspan="2">준비물</th>
</tr>
<tr>
<th>학용품</th>
<th>가격</th>
</tr>
</thead>
<tbody>
<tr>
<td>가위</td>
<td>1000원</td>
</tr>
<tr>
<td>풀</td>
<td>500원</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>합계</th>
<th>1500원</th>
</tr>
</tfoot>
</table>
table,
th,
td {
border: 1px solid grey;
border-collapse: collapse;
padding: 10px;
}