ガレコレ
Garage Collection
 
2016年4月16日(土)
表の行色 #HTML5&CSS3&JavaScript

 HTMLの表をExcelみたくできないの?とよく尋ねられます。CSS3で出来ます。まずは、行色を交互に替える方法です。

--プログラム--
<!DOCTYPE html>
<html lang="ja">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">

<style>

table {margin:16px 0px;}

tr:nth-child(odd)  {background:gold;}
tr:nth-child(even) {background:yellow;}

table.aqua tr:nth-child(odd)  {background:aqua;}
table.aqua tr:nth-child(even) {background:aliceblue;}

table.orange tr:nth-child(1)  {background:orange;}

table.calendar tr {background:lemonchiffon;}
table.calendar tr:nth-child(7n+6)  {background:aqua;}
table.calendar tr:nth-child(7n)    {background:pink;}

</style>

</head>

<body>

<table border="1">
<tr><th>1</th><td>a</td></tr>
<tr><th>2</th><td>b</td></tr>
<tr><th>3</th><td>c</td></tr>
<tr><th>4</th><td>d</td></tr>
<tr><th>5</th><td>e</td></tr>
</table>

<table border="1">
<tr><th>1</th><td>a</td></tr>
<tr><th>2</th><td>b</td></tr>
<tr><th>3</th><td>c</td></tr>
<tr><th>4</th><td>d</td></tr>
<tr><th>5</th><td>e</td></tr>
</table>

<table border="1" class="aqua">
<tr><th>1</th><td>a</td></tr>
<tr><th>2</th><td>b</td></tr>
<tr><th>3</th><td>c</td></tr>
<tr><th>4</th><td>d</td></tr>
<tr><th>5</th><td>e</td></tr>
</table>

<table border="1" class="orange">
<tr><th>No.</th><th>name</th></tr>
<tr><th>1</th><td>a</td></tr>
<tr><th>2</th><td>b</td></tr>
<tr><th>3</th><td>c</td></tr>
<tr><th>4</th><td>d</td></tr>
<tr><th>5</th><td>e</td></tr>
</table>

<table border="1" class="calendar">
<tr><th>1</th><td>月</td></tr>
<tr><th>2</th><td>火</td></tr>
<tr><th>3</th><td>水</td></tr>
<tr><th>4</th><td>木</td></tr>
<tr><th>5</th><td>金</td></tr>
<tr><th>6</th><td>土</td></tr>
<tr><th>7</th><td>日</td></tr>
<tr><th>8</th><td>月</td></tr>
<tr><th>9</th><td>火</td></tr>
<tr><th>10</th><td>水</td></tr>
<tr><th>11</th><td>木</td></tr>
<tr><th>12</th><td>金</td></tr>
<tr><th>13</th><td>土</td></tr>
<tr><th>14</th><td>日</td></tr>
<tr><th>15</th><td>月</td></tr>
<tr><th>16</th><td>火</td></tr>
<tr><th>17</th><td>水</td></tr>
<tr><th>18</th><td>木</td></tr>
<tr><th>19</th><td>金</td></tr>
<tr><th>20</th><td>土</td></tr>
<tr><th>21</th><td>日</td></tr>
<tr><th>22</th><td>月</td></tr>
<tr><th>23</th><td>火</td></tr>
<tr><th>24</th><td>水</td></tr>
<tr><th>25</th><td>木</td></tr>
<tr><th>26</th><td>金</td></tr>
<tr><th>27</th><td>土</td></tr>
<tr><th>28</th><td>日</td></tr>
<tr><th>29</th><td>月</td></tr>
<tr><th>30</th><td>火</td></tr>
<tr><th>31</th><td>水</td></tr>
</table>

</body>

</html>
--

 タグ名:は疑似クラスと言われるもので、そのタグの内、条件に合ったものを示します。nth-child()は、n番目の子供ということです。nth-child(1)は1番目、oddは奇数、evenは偶数を表します。

奇数・・・nth-child(odd) または nth-child(2n+1)
偶数・・・nth-child(even) または nth-child(2n)

 tableにクラス名を与えておくことで、その表だけのスタイルが指定できます。
http://neconote.jp/html5/table_nth-child.html
 
お問い合わせ
by Network Communication Note