focus-within プロパティを使ったformを作ってみました。
従来、下位要素から、上位要素の指定はCSSでは出来ませんでしたが、CSS4の片りんを見た感じですね。
Demo
HTML
<form action="" method="get"> <div class="intro-content-1"> <input type="url" name="my_url" placeholder="URLを入力してね"> <p class="description">説明文:Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="alert">URLの入力値が不正です</p> </div> <div class="intro-content-2"> <input type="email" name="my_email" placeholder="Emailを入力してね"> <p class="description">説明文:Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="alert">Emailの入力値が不正です</p> </div> <input type="submit" value="送信"> </form>
CSS
div[class |="intro-content"]{ visibility:hidden; position:relative; } .alert, .description{ position:absolute; clip: rect(1px, 1px, 1px, 1px); overflow:hidden; } div[class |="intro-content"]:focus-within input:invalid ~ .alert, div[class |="intro-content"]:focus-within .description{ clip:auto; position:static; } div[class |="intro-content"]:focus-within{ visibility:visible; } input:invalid ~ .alert, input, input:placeholder-shown{ visibility:visible; } .alert{ color:#f00; font-weight:bold; }
Photo by Viktor Mogilat on Unsplash
:focus-within