Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style empty textbox - CSS only solution

Tags:

html

css

is-empty

Update - Mar-24-2016

I wanted to generalize the concerns but looks like it has been comprehended to be specific, my bad. This answer is is 100% solution to the example I used earlier.

enter image description here

Please refer this CodePen

So the idea behind Style empty textbox, was

textbox:empty ~ label {
 // position it as floating label
}

Looks like it is not possible in CSS right now, may be in future.

Thank you every one for your help.

Update - Mar-23-2016

This answer is close. But using :invalid is not an option, as it makes the field mandatory with required=true attribute.


empty and non empty state's style

Please refer this CodePen for the desired behavior, with javascript.The demo is for the sake of explaining, how it should behave, using javascript is not the intended behavior. Also the color used is just for the sake of contrast, is has nothing to do with validation


Is there any way to style an empty textbox with CSS only?

I tried :empty pseudo-class, unfortunately textbox is always detected as empty; as it has no children or text-node. To be precise, textbox is a self-closing tag.

The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered.

Any pointer would be helpful.

like image 407
Sarbbottam Avatar asked Mar 24 '16 01:03

Sarbbottam


1 Answers

This can be achieved with the use of :invalid and setting the input to required="true"

input { 
  padding: 10px;
  background-color:red; 
}
input:invalid {
  background-color:lightblue;
}
<input id="in1" required="true">

MDN :invalid

like image 181
Gerard Sexton Avatar answered Oct 20 '22 12:10

Gerard Sexton