Search code examples
csscss-selectors

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

Solution

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