Created
June 22, 2026 07:17
-
-
Save amane-katagiri/2f8aa285f72e8dff248ffe9d3d17bfde to your computer and use it in GitHub Desktop.
あまねけ!おもしろCSS 7選 サンプルページ ⑥ CSSだけでクリックに応じてスタイルを切り替える
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="ja"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>あまねけ!おもしろCSS 7選 サンプルページ ⑥ CSSだけでクリックに応じてスタイルを切り替える</title> | |
| <style> | |
| /* 「状態」を保持するチェックボックスを隠しつつフォーカス可能にする */ | |
| input[type="checkbox"]#toggle { | |
| position: absolute; | |
| pointer-events: none; | |
| clip-path: rect(0 0 0 0); | |
| opacity: 0; | |
| appearance: none; | |
| } | |
| /* ユーザーに提示する切り替えUI */ | |
| label#toggle-button { | |
| border: 1px solid; | |
| border-radius: 0.5em; | |
| padding: 0.5em; | |
| background-color: skyblue; | |
| } | |
| label#toggle-button::before { | |
| content: "ここをクリックして青色に変更"; | |
| } | |
| input[type="checkbox"]#toggle:checked ~ label#toggle-button { | |
| background-color: pink; | |
| } | |
| input[type="checkbox"]#toggle:checked ~ label#toggle-button::before { | |
| content: "ここをクリックして赤色に変更"; | |
| } | |
| input[type="checkbox"]#toggle:focus ~ label#toggle-button { | |
| outline: 2px solid royalblue; | |
| } | |
| /* 切り替えるスタイルの定義 */ | |
| body { | |
| margin: 0; | |
| padding: 0; | |
| text-align: center; | |
| } | |
| #main { | |
| background-color: red; | |
| padding: 1em; | |
| margin-bottom: 1em; | |
| } | |
| #message::before { | |
| content: "エラー: "; | |
| } | |
| input[type="checkbox"]#toggle:checked ~ #main { | |
| color: #eee; | |
| background-color: blue; | |
| } | |
| input[type="checkbox"]#toggle:checked ~ #main #message::before { | |
| content: "情報: "; | |
| } | |
| .share-text { | |
| user-select: all; | |
| border-bottom: 1px dotted; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <input id="toggle" type="checkbox"> | |
| <section id="main"> | |
| <div id="message"><span class="share-text">百合小説・エッセイ・技術・怪文書・生活・写真・団地・転籍届・こうかんノート・Web・架空・廃墟</span></div> | |
| </section> | |
| <label id="toggle-button" for="toggle"></label> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment