2

I've got an input box. I customise it in normal state and on focus.

My question is how do I keep the focus CSS styling if text is present in the input box?

.par input[type=sample]{
    width:75px;
    background-color: #000;
}
.par input[type=sample]:focus{
    width:50px;
    background-color: #FF0;
}
Harry
  • 87,580
  • 25
  • 202
  • 214
Becky
  • 5,467
  • 9
  • 40
  • 73

3 Answers3

6

There are no pure CSS selectors to directly select and style text boxes based on their content. But if the field is a mandatory field (that is, you could add the required attribute) then the :valid pseudo selector can be used to identify if the text box has any text type inside it or not and based on it apply the required styles.

input[type=text] {
  width: 75px;
  background-color: #000;
}
input[type=text]:focus,
input[type=text]:valid {
  width: 50px;
  background-color: #FF0;
}
<input type="text" required />
<input type="text" required />
Harry
  • 87,580
  • 25
  • 202
  • 214
0
input[value=""]:focus {
    background-color: yellow;
}

<input onkeyup="this.setAttribute('value', this.value);" value="" />

another way would be to check in jquery.. using ':contains' selector

SuperNova
  • 25,512
  • 7
  • 93
  • 64
-1

you can have one more selector with :valid pseudo-class.

.par input[type=sample]:valid{
     width:50px;
     background-color: #FF0;
   }
Mahesh
  • 325
  • 1
  • 2
  • 11