Web Form 疑似クラスの使い方

フォームの疑似クラスと疑似要素

疑似クラスはフォームのさまざまな状態をスタイリングします。 疑似クラスには次のようなものがあります。 :hover マウスのカーソルが重なったとき :focus マウスで選択されたとき :active 要素がアクティブ化されているとき :required 必須のとき :optional オプションのとき :valid 有効なとき :invalid 無効なとき :in-range レンジ内 :out-of-range レンジ外 :enabled 可能 :disabled 不可能 :read-only 読み専用 :read-write 読み書き可能 :checked チェック時 :indeterminate 不確定な状態 :default デフォルト時 疑似要素は、疑似クラスと同じようにフォームの状態をスタイリングします。 疑似要素には次のようなものがあります。 ::before 要素の表示の前側 ::after 要素の表示の後ろ側

疑似クラスと疑似要素の使用例

上の画像は疑似クラスと疑似要素の使用例です。 form.htmlのコードは次の様になります。

<form> <fieldset> <legend>返信</legend> <p>入力は必須です。</p> <div> <label for="name">お名前: </label> <input id="name" name="name" type="text" required> <span></span> </div> <div> <label for="age">年齢 (18才以上): </label> <input id="age" name="age" type="number" min="18" max="60" required> <span></span> </div> <div> <label for="email">Email:</label> <input id="email" name="email" type="email" required> <span></span> </div> <div><button>送信</button></div> </fieldset> </form>

form.cssのコードは次の様になります。 難しい箇所は説明を付けています。

body { font-family: sans-serif; margin: 20px auto; max-width: 460px; } fieldset { padding: 10px 30px 0; } legend { color: white; background: black; padding: 5px 10px; } fieldset > div { margin-bottom: 20px; display: flex; flex-flow: row wrap; } fieldset子のdiv要素 button, label, input { display: block; font-size: 100%; padding: 0; margin: 0; box-sizing: border-box; width: 100%; padding: 5px; height: 30px; } input { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } input:hover, input:focus { background-color: #eee; } inputの:hoverと:focusの時 input + span { position: relative; } inputに隣接するspan positionは相対的 input + span::after { font-size: 0.7rem; position: absolute; padding: 5px 10px; top: -26px; } inputに隣接するspanの表示の後ろ側 input:required + span::after { color: white; background-color: black; content: "required"; left: -70px; } inputが必須の時と、 inputに隣接するspanの表示の後ろ側 input:out-of-range + span::after { color: white; background-color: red; width: 155px; content: "年齢制限(18~60)"; left: -182px; } inputがレンジ外の時、 inputに隣接するspanの表示の後ろ側 input + span::before { position: absolute; right: -20px; top: 5px; } inputに隣接するspanの表示の前側、 positionは絶対的 input:invalid { border: 2px solid red; } inputが無効の時 input:invalid + span::before { content: '✖'; color: red; } inputが無効の時と、 inputに隣接するspanの表示の前側 input:valid + span::before { content: '✓'; color: green; } inputが有効の時と、 inputに隣接するspanの表示の前側 button { width: 60%; margin: 0 auto; }

以上です。