배경색을 만드는 속성
배경 색상은 background-color 속성으로 만듭니다. table, tr, th, td, thead, tbody, tfoot에 배경색을 적용할 수 있습니다.
예제
기본 모양
- 다음 표를 기본으로 하고, 배경색을 여러 곳에 추가해보겠습니다.
<table>
<thead>
<tr>
<th>Lorem</th><th>Ipsum</th><th>Dolor</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td>
</tr>
<tr>
<td>Lorem</td><td>Ipsum</td><td>Dolor</td>
</tr>
<tbody>
</table>
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
표 전체에 배경색 추가하기
-
표 전체에 하나의 배경색을 넣을 때는
<table>
에 배경색을 추가하는 게 편합니다.
table {
width: 100%;
border-top: 1px solid #444444;
border-collapse: collapse;
background-color: #bbdefb;
}
th, td {
border-bottom: 1px solid #444444;
padding: 10px;
text-align: center;
}
제목이 있는 행과 내용이 있는 행에 다른 색 추가하기
-
<th>
요소와<td>
요소에 서로 다른 배경색을 추가합니다.
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;
}
행의 배경색을 번갈아 넣기
-
홀수번째 행과 짝수번째 행의 배경색을 다르게 하고 싶다면
<tr>
요소에 nth-child 선택자를 이용하여 배경색을 추가합니다.
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: white;
}
tbody tr:nth-child(2n) {
background-color: #bbdefb;
}
tbody tr:nth-child(2n+1) {
background-color: #e3f2fd;
}
열의 배경색을 번갈아 넣기
-
홀수번째 열과 짝수번째 열의 배경색을 다르게 하고 싶다면
<th>
또는<td>
요소에 nth-child 선택자를 이용하여 배경색을 추가합니다.
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: white;
}
td:nth-child(2n) {
background-color: #bbdefb;
}
td:nth-child(2n+1) {
background-color: #e3f2fd;
}