데이터를 행(row)과 열(column)로 이루어진 테이블 형식으로 만들고 싶을 때 사용한다.
<table>
table 정의
모든 table 생성의 시작은 <table></table> 태그이다.
<td>
table의 한 셀(cell) 정의
다른 태그 없이 <td> 태그만 사용하면 같은 행에서 자동으로 정렬된다.
근데 우리가 원한는건 table 형식이므로 행을 만드는 <tr>태그로 감싸주어야한다.
<tr>
table의 행(row) 정의
<table>
<tr>
<td>Person 1</td>
<td>Person 2</td>
<td>Person 3</td>
</tr>
<tr>
<td>Snoopy</td>
<td>Brown</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
별다른 CSS코드 없이 HTML코드를 실행시킨 결과이다.
<th>
셀(cell)의 데이터 유형을 의미하는 헤더(header) 정의
위 예시는 person 3명에 대한 정보를 담고 있는 코드이므로 Person1 Person2 Person3을 다른 셀과 구분시키고 싶다. 이럴 때는 <td> 대신 <th> 태그를 사용한다.
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Snoopy</td>
<td>Brown</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
일반 셀이 아닌 헤더를 나타낸다는 점을 제외하면 셀을 정의하는 <td>와 완전히 동일하게 작동한다.
<th> text의 기본값은 bold와 centered이다. (CSS로 바꿀 수 있음)
table을 만들다 보면 다음과 같이 셀이 여러 행이나 열에 걸쳐 있어야 할 때가 있다.
이럴 때는 colspan과 rowspan을 사용한다.
결과 구분을 도와줄 CSS코드도 함께 실행시켜 보자.
html {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border: 2px solid rgb(200,200,200);
letter-spacing: 1px;
font-size: 0.8rem;
}
td, th {
border: 1px solid rgb(190,190,190);
padding: 10px 20px;
}
th {
background-color: rgb(235,235,235);
}
td {
text-align: center;
}
tr:nth-child(even) td {
background-color: rgb(250,250,250);
}
tr:nth-child(odd) td {
background-color: rgb(245,245,245);
}
caption {
padding: 10px;
}
-> minimal-table.css
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Animals table</title>
<link href="minimal-table.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Animals table</h1>
<table>
<tr>
<th colspan="2">Animals</th>
</tr>
<tr>
<th colspan="2">Hippopotamus</th>
</tr>
<tr>
<th rowspan="2">Horse</th>
<td>Mare</td>
</tr>
<tr>
<td>Stallion</td>
</tr>
<tr>
<th colspan="2">Crocodile</th>
</tr>
<tr>
<th rowspan="2">Chicken</th>
<td>Hen</td>
</tr>
<tr>
<td>Rooster</td>
</tr>
</table>
</body>
</html>