LoginSignup
0
0

CSSの疑似クラスhasを使ってHTMLでテーブル行に背景色をひく

Posted at

HTMLでテーブル組むとき「チェックボックスにチェックしたら、行全体に背景色を引きたい」というときがあります。昔はJavaScriptとの組み合わせでしたが、CSSの疑似クラスである has で実現できます。

HTML

<table>
 <tbody>
   <tr>
     <td> <input type="checkbox" id="checkbox1"> </td>
     <td> <label for="checkbox1">チェックボックスのアイテム</label> </td>
   </tr>
 </tbody>
</table>
</html>

CSS

table tbody:has(input[type=checkbox]:checked) tr td {
  background-color: blue;
}

チェックボックスが td の下にあるので、CSSセレクタを次のように書きたくなりますが、

table tbody tr td:has(input[type=checkbox]:checked) 

「テーブルの行に対して色をひきたい」ので、tbody:has のようにします。
を設定しておけば、ラベルを押しても、チェックボックスを押しても効果が発動します。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0