I-006 Interaction simple

How to create a toggle switch トグルスイッチの作り方

ON/OFF toggle switch. collect UI-style pattern. ON/OFF を切り替えるトグルスイッチ。collect UI 系のパターン。

ライブデモ Live Demo

OFF
0.25s

概要・用途・特徴Overview, Usage & Features

何ができるかWhat it does

ON/OFF toggle switch. collect UI-style pattern.

ON/OFF を切り替えるトグルスイッチ。collect UI 系のパターン。

どこで使うかWhere to use

user engagement, data entry, content management, settings panel

設定パネル、機能フラグ、フォーム設定、ダッシュボードコントロール

特徴Key features

Fully custom toggle switch replacing the native checkbox with accessible semantics preserved. CSS-only visual with smooth knob slide animation. Customizable size, track color (on/off), and knob size via CSS variables. Works with keyboard and screen readers.

ネイティブチェックボックスを置き換えつつアクセシブルセマンティクスを保持したカスタムトグルスイッチ。スムーズなノブスライドアニメーションのCSSオンリービジュアル。サイズ・トラック色(オン/オフ)・ノブサイズをCSSカスタムプロパティで調整可能。キーボードとスクリーンリーダー対応。

調整可能パラメータ Adjustable Parameters

Parameter Default Description

実装コード Implementation Code

// react/I-006.jsx
import { useState } from "react";
import "./I-006.css";

export default function ToggleSwitch({ defaultChecked = false, onChange }) {
  const [checked, setChecked] = useState(defaultChecked);

  const handleClick = () => {
    setChecked((prev) => !prev);
    onChange?.(!checked);
  };

  return (
    <div className="toggle-wrap">
      <button
        type="button"
        className={"toggle-switch" + (checked ? " on" : "")}
        role="switch"
        aria-checked={checked}
        onClick={handleClick}
      />
      <span className="toggle-label">{checked ? "ON" : "OFF"}</span>
    </div>
  );
}
/* react/I-006.css */
:root {
  --toggle-duration: 0.25s;
  --toggle-width: 52px;
  --toggle-height: 28px;
  --toggle-knob: 22px;
}

.toggle-wrap { display: flex; align-items: center; gap: 12px; }

.toggle-switch {
  position: relative;
  width: var(--toggle-width);
  height: var(--toggle-height);
  min-height: var(--toggle-height);
  padding: 0;
  border: none;
  background: #cbd5e0;
  border-radius: 999px;
  cursor: pointer;
  transition: background var(--toggle-duration) ease;
  flex-shrink: 0;
}

.toggle-switch.on { background: #5c6ac4; }

.toggle-switch::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 3px;
  width: var(--toggle-knob);
  height: var(--toggle-knob);
  margin-top: calc(var(--toggle-knob) / -2);
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
  transition: transform var(--toggle-duration) ease;
}

.toggle-switch.on::after {
  transform: translateX(calc(var(--toggle-width) - var(--toggle-knob) - 6px));
}

.toggle-label { font-weight: 600; color: var(--text, #1d2242); }
import { useState } from "react";
import "./I-006.css";

export default function ToggleSwitch({ defaultChecked = false, onChange }) {
  const [checked, setChecked] = useState(defaultChecked);

  const handleClick = () => {
    const next = !checked;
    setChecked(next);
    onChange?.(next);
  };

  return (
    <div className="toggle-wrap">
      <button
        type="button"
        className={"toggle-switch" + (checked ? " on" : "")}
        role="switch"
        aria-checked={checked}
        onClick={handleClick}
      />
      <span className="toggle-label">{checked ? "ON" : "OFF"}</span>
    </div>
  );
}
:root {
  --toggle-duration: 0.25s;
  --toggle-width: 52px;
  --toggle-height: 28px;
  --toggle-knob: 22px;
}

.toggle-wrap { display: flex; align-items: center; gap: 12px; }

.toggle-switch {
  position: relative;
  width: var(--toggle-width);
  height: var(--toggle-height);
  min-height: var(--toggle-height);
  padding: 0;
  border: none;
  background: #cbd5e0;
  border-radius: 999px;
  cursor: pointer;
  transition: background var(--toggle-duration) ease;
  flex-shrink: 0;
}

.toggle-switch.on { background: #5c6ac4; }

.toggle-switch::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 3px;
  width: var(--toggle-knob);
  height: var(--toggle-knob);
  margin-top: calc(var(--toggle-knob) / -2);
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
  transition: transform var(--toggle-duration) ease;
}

.toggle-switch.on::after {
  transform: translateX(calc(var(--toggle-width) - var(--toggle-knob) - 6px));
}

.toggle-label { font-weight: 600; color: var(--text, #1d2242); }

仕組みとカスタマイズHow It Works & Customization

仕組みHow it works

A visually hidden <input type="checkbox"> is paired with a <label> styled as the toggle track and knob. The knob (label::after) translates along the X-axis when the checkbox is :checked. CSS adjacent sibling or :has() selectors link the input state to the visual label. JavaScript adds aria-checked and handles change events.

視覚的に非表示の<input type="checkbox">がトグルトラックとノブとしてスタイリングされた<label>とペアになります。チェックボックスが:checkedの時、ノブ(label::after)がX軸方向にトランスレート。CSS隣接兄弟セレクタまたは:has()セレクタが入力状態を視覚的なラベルにリンク。JavaScriptがaria-checkedを追加しchangeイベントを処理。

カスタマイズ方法Customization

Scale up by multiplying all sizes proportionally via a single scale factor variable. Add a sun/moon icon inside the knob for a theme toggle variant. Animate the track background color transition independently for a more polished feel.

単一スケールファクター変数ですべてのサイズを比例拡大。テーマトグルバリアントとしてノブ内に太陽/月アイコンを追加。よりポリッシュされた感触のためにトラックの背景色トランジションを独立してアニメーション。

注意点Caveats

Never remove the underlying <input> from the DOM — only visually hide it (clip / opacity / size: 0) to maintain native form submission and keyboard accessibility. Add role="switch" and aria-checked to the visible element when not using the native input approach.

ネイティブフォーム送信とキーボードアクセシビリティを維持するため、基礎となる<input>をDOMから削除せず視覚的に非表示にするだけにしてください(clip/opacity/size:0)。ネイティブ入力アプローチを使用しない場合は、可視要素にrole="switch"とaria-checkedを追加してください。

よくある質問 Frequently Asked Questions

How to customize the toggle switch? Toggle Switchをカスタマイズするには?

Modify the CSS custom properties and class styles defined in the code section. Key adjustable values include colors, sizes, durations, and spacing. See the Adjustable Parameters section for specific variables.

コードセクションで定義されているCSSカスタムプロパティとクラススタイルを変更してください。色、サイズ、時間、間隔が主な調整可能値です。具体的な変数は調整可能パラメータセクションを参照してください。

How to use the toggle switch in React? ReactでToggle Switchを使うには?

Import the provided React component and its CSS file. The component accepts props for customization. Check the React code section for the full implementation and available props.

提供されているReactコンポーネントとCSSファイルをインポートしてください。コンポーネントのpropsでカスタマイズできます。完全な実装と利用可能なpropsはReactコードセクションを参照してください。

What are the performance implications of toggle switch? Toggle Switchのパフォーマンスへの影響は?

This implementation uses CSS transforms and opacity for animations, which are GPU-accelerated. It's lightweight and doesn't cause layout thrashing. Consider using prefers-reduced-motion for accessibility.

この実装はCSSのtransformとopacityを使用しており、GPUアクセラレーションされます。軽量でレイアウトスラッシングを引き起こしません。アクセシビリティのためにprefers-reduced-motionの使用を検討してください。

AIへの指示テンプレート AI Prompt Template

以下をAIに貼り付けると実装を依頼できます。 Paste the following into your AI assistant to request implementation.