CSS / Tutorial / 표 꾸미기 / 배경색
목차
배경색을 만드는 속성
- 배경색은 background-color 속성으로 만듭니다.
- table, tr, th, td, thead, tbody, tfoot에 적용할 수 있습니다.
기본 모양
- 다음 표를 기본으로 하고, 배경색을 여러 곳에 추가해보겠습니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>CSS</title>
<style>
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Lorem</th><th>Ipsum</th><th>Dolor</th><th>Sit</th><th>Amet</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td><td>Sit</td><td>Amet</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td><td>Sit</td><td>Amet</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td><td>Sit</td><td>Amet</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td><td>Sit</td><td>Amet</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td><td>Sit</td><td>Amet</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td><td>Sit</td><td>Amet</td>
</tr>
</tbody>
</table>
</body>
</html>

표 전체에 배경색 추가하기
- 표 전체에 하나의 배경색을 넣을 때는 table에 배경색을 추가하는 게 편합니다.
<style>
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
table {
background-color: #bbdefb;
}
</style>

제목이 있는 행과 내용이 있는 행에 다른 색 추가하기
- th 요소와 td 요소에 서로 다른 배경색을 추가합니다. (thead 요소와 tbody 요소에 서로 다른 배경색을 추가해도 됩니다.)
<style>
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
th {
background-color: #bbdefb;
}
td {
background-color: #e3f2fd;
}
</style>

행의 배경색을 번갈아 넣기
- 홀수번째 행과 짝수번째 행의 배경색을 다르게 하고 싶다면 tr 요소에 nth-child 선택자를 이용하여 배경색을 추가합니다.
<style>
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
thead tr {
background-color: #0d47a1;
color: #ffffff;
}
tbody tr:nth-child(2n) {
background-color: #bbdefb;
}
tbody tr:nth-child(2n+1) {
background-color: #e3f2fd;
}
</style>

열의 배경색을 번갈아 넣기
- 홀수번째 열과 짝수번째 열의 배경색을 다르게 하고 싶다면 th 또는 td 요소에 nth-child 선택자를 이용하여 배경색을 추가합니다.
<style>
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
th:nth-child(2n), td:nth-child(2n) {
background-color: #bbdefb;
}
th:nth-child(2n+1), td:nth-child(2n+1) {
background-color: #e3f2fd;
}
</style>









