19

I would like to apply a special style to all inputs in my form that are required and empty at that.

It does work when i write in my css

input[required='required'] {
    bla-bla-bla;
}

but it doesn't work, when i write

input[value=''] {
   bla-bla-bla;
}

I know i can do that using jQuery, but i would like to do that in pure css, if it is possible.

Can that be done?

Thank you in advance,
Timofey.

John
  • 29,546
  • 11
  • 78
  • 79
Ibolit
  • 9,218
  • 7
  • 52
  • 96
  • possible duplicate of [Matching an empty input box using CSS](http://stackoverflow.com/questions/3617020/matching-an-empty-input-box-using-css) – hakre Jan 16 '15 at 09:18

4 Answers4

23

If you don't have to support older IE versions, you can set the placeholder attribute on your input to something (can be whitespace, but must be something) and use :placeholder-shown to target that input.

<input type="text" class="custom-input" placeholder=" ">
.custom-input:placeholder-shown {
    /* Your rules */
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
TommyZG
  • 500
  • 3
  • 13
14

You can use the Pseudo-Selecot :invalid for this - it will match an input only when the browser-validation fails for the element. If you set the element required it will be invalid as long as it is empty.

And all moder browsers support this CSS-class: Browser Compatibility

input:invalid {
  border-color: red;
}
<input type="text" required>
Falco
  • 3,287
  • 23
  • 26
  • What if I don't want to have the input required? – Fanky Sep 02 '21 at 07:46
  • @Fanky If you want the style to auto-update without JavaScript you will need required or use the placeholder tag. But with a file-input you will most likely involve JavaScript anyway. – Falco Sep 02 '21 at 09:25
  • Well yes, I ended up with `jQuery( 'input[type=file]' ).change( function( e ) { this.defaultValue = this.value; } );` and CSS `:not([value=""])` which doesn't work without the former. – Fanky Sep 02 '21 at 09:41
7

Searched css style empty inputs and found the following:

Matching an empty input box using CSS

You need to use JavaScript.

To use the CSS style, you would have to type in the attribute: value='' in your HTML, but then the CSS would match regardless of if the value changes mid-session.

Community
  • 1
  • 1
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
1

Try this

<input type="text" value="">
input:not([value=""]) {
    /* Your code */
}
Ying-Shan Lin
  • 607
  • 5
  • 22