html - How to target label element based on input element's dynamic class? -


html

<label for="email">email</label> <input type="text" name="email"></input> 

the class attribute of email input element may change, if user enters invalid email format. want label change red when input it's gets class "invalid".

in fact, want labels for attribute "invalid aware" of assigned input elements.

css attempt:

label[for=*.invalid]{      color: red; } 

the above incorrect because might have specify specific form element name.

option 1

if you're adding dynamic class input element (.invalid), why not add class label element, well? simplify styling of label when input fails validation.

option 2

i understand changing label color red highlights error user. in option still highlight error user, in different way. css :valid , :invalid pseudo-classes represent form , input elements validate or fail validate. these pseudo-classes style input not label.

option 3

this option involves sibling , attribute selectors. have reverse order of label , input in html (but doesn't have change appearance on screen; see below).

html

<input type="text" name="email" class="invalid"></input> <label for="email">email</label> 

css

input[class="invalid"] + label { color: red; } 

changing visual order of elements css flexbox

despite order of elements in dom, can still change visual order of elements css flexbox. if didn't want put label after input sake of appearance there's easy workaround: wrap input , label in flexbox , use order property arrange display order.


a few side notes...

  • html5 provides input type="email"‌, may want consider instead of type="text". 1 benefit being when mobile devices see type="email" launch e-mail-friendly keyboard.

  • second, input element void element. no closing tag required. can safely remove </input>.

  • lastly, for attribute associates label element matching id. in code, need add id="email" input label click feature work.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -