サイトアイコン WorldPress Fun

CSSの:has()疑似クラスを使った超簡単フォームの切り替えボタン



javascriptなし。cssだけで実装。

inputタグのradioを使っているので、フォームでちゃんと使える
(なぜかinput使ってない見た目だけのサンプルが多い

ボタンサイズの指定もないので、日本語入れても崩れない
(なぜか、OnOff以外入れられないサンプルが多い

重要なのはこのcssのセレクタで子要素のinputがcheckedされたときだけスタイルが適用されるようになっていること。
label:has(input:checked) {}

最低限のcssだけなので、ここから角丸にしたり、ホバーのアクション入れたりいろいろカスタマイズ可能。
これならtailwindだけでも実装できるので、気が向いたら作ってみたい。

ちなみに、has()はなぜか今はfirefoxでデフォルト非対応らしいので注意。
https://developer.mozilla.org/ja/docs/Web/CSS/:has

以下、ソース


<style>
.btn-group {
  padding-left: 1px;
  display: inline-flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
label {
  display: inline-block;
  position: relative;
  padding: 5px 10px;
  margin: 0 0 0 -1px;
  border: #7e8993 solid 1px;
  flex: 1;
  text-align: center;
  white-space: nowrap;
  z-index: 1;
}
.btn-group input {
  display: none !important;
}
label:has(input:checked) {
  background: #008dd4;
  color: #fff;
  z-index: 2;
}
</style>

<div>
  <div class="btn-group">
    <label><input type="radio" name="r1" value="true" checked="checked">On</label>
    <label><input type="radio" name="r1" value="false"> Off</label>
  </div>
</div>
<div>
  <div class="btn-group">
    <label><input type="radio" name="r2" value="true" checked="checked">有効にする</label>
    <label><input type="radio" name="r2" value="false">無効にする</label>
  </div>
</div>
モバイルバージョンを終了