CSSでinputに入力したらlabelのスタイルが変更されるようにする

Ads

Result


:placeholder-shown疑似クラスを使ってlabelのスタイルを入力の有無でスイッチします

css

.input-label {
  color: blue;
}
.input :not(*):placeholder-shown, .input-label {/*入力されたとき*/
  color: green;
}
.input-control:placeholder-shown ~ .input-label {/*入力されてないとき*/
  color: red;
}

html

<div class="input">
	<input class="input-control" id="input" placeholder="hogehoge" />
	<label class="input-label" for="input">入力すると色が変わります</label>
</div>

can i use


各ブラウザの対応状況です。IEは別途、何かしら対応する必要がありそうです

via

タイトルとURLをコピーしました