Becky
Becky

Reputation: 5585

Keep focus styling if text is present

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;
}

Upvotes: 2

Views: 2002

Answers (4)

Lyokolux
Lyokolux

Reputation: 1417

As of 2024-12-02, the pseudo-selector :placeholder-shown is widely supported.

It targets all inputs with a visible placeholder. When an input has a value, the placeholder is hidden.

Combine it with :not(:placeholder-shown) and it targets input where placeholders are invisible.

So input:not(:placeholder-shown) can be a way to go (independent of the field validity).

input {
border: 1px solid black
}

input:not(:placeholder-shown) {
 color: green;
 border-color: green;
}
<input placeholder="" value="Some value" />
<input placeholder="" value="" />
<input placeholder=""  />

Upvotes: 0

Mahesh
Mahesh

Reputation: 355

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

.par input[type=sample]:valid{
     width:50px;
     background-color: #FF0;
   }

Upvotes: -1

SuperNova
SuperNova

Reputation: 27446

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

Upvotes: 0

Harry
Harry

Reputation: 89750

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 />

Upvotes: 6

Related Questions