Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS highlight label BEFORE an invalid input

Tags:

css

Ciao, I have this element here:

<div class="uk-form-row">
    <div class="md-input-wrapper md-input-filled md-input-focus">
        <label>Label</label>
        <input type="text" class="md-input">
        <span class="md-input-bar"></span>
    </div>
</div>

This is from a material design theme (Altair Admin v2) so the element once the page is loaded does this:

enter image description here

As you can see the label is moving around (but maybe is not a big deal).

With other elements, if they are empty (invalid) I can underline them or change their color using css:

input:invalid::-webkit-input-placeholder{
    color: #e53935 !important;
}

But being this a label BEFORE the input I don't know how I can select it with CSS. How do I turn the LABEL into a different color if the input is invalid?

like image 275
Mr.Web Avatar asked Nov 15 '17 12:11

Mr.Web


2 Answers

Look at CSS code (simplified to illustrate my point):

.md-input-wrapper {
  position: relative;
}

.md-input-wrapper > label {
  position: absolute;
  top: 16px;
  left: 4px;
  right: 0;
}

Label is positioned absolutely relative to wrapper, so you can put label element after input element in HTML:

<div class="md-input-wrapper">
    <input type="text" class="md-input">
    <span class="md-input-bar"></span>
    <label>Label</label>
</div>

After that, you can use General sibling combinator to select label of invalid input:

input:invalid ~ label { 
   color: red; 
}
like image 102
fen1x Avatar answered Nov 15 '22 07:11

fen1x


There is a simpler way to get this done. The :valid and :invalid pseudo-classes will automatically bubble up to a parent <fieldset>. Here is the reference.

You can take advantage of this fact to style your label like so:

<fieldset>
  <label>Label</label>
  <input type="text" />
</fieldset>

Then in your CSS

fieldset:invalid > label:first-of-type {
  color: #e53935 !important;
}

So if your input is :invalid it will invalidate your fieldset, which you can then reference to style your label.

like image 21
Adam Avatar answered Nov 15 '22 09:11

Adam