Search code examples
csscss-specificity

Applying CSS color to text input but still be able to override it with a class


I'm trying to figure out how to specify a default style for text inputs that can still be overridden. In this case, I would like the second input to have a red background, however it has the same background as the first input.

input[type=text] {
  box-sizing: border-box;
  width: 100%;
  color: white;
  background: #99C;
}

.error {
  color: white;
  background: red;
  padding: 0.5em;
}
<input type=text value=XYZZY><br>
<input type=checkbox> XYZZY<br>
<input type=text class=error value=XYZZY><br>
<div class=error>XYZZY</div>

If I remove the [type=text] from the input rule it fixes the problem for the second text area, but it makes the style apply to the checkbox as well (which I don't want.)

I can change the .error rule to .error, input.error but I don't want to have to do that for every class I might possibly want to apply to a text input.

Is there some way to make the [type=text] rule less specific while still only applying to text inputs so that it doesn't get applied in preference to straight class rules?


Solution

  • I just found that I can artificially increase the specificity of a rule by duplicating the class. Instead of .error I can write .error.error. This appears to allow the rule to be more specific than the [type=text] rule while still allowing it to be overridden in a sane manner:

    input[type=text] {
      box-sizing: border-box;
      width: 100%;
      color: white;
      background: #99C;
    }
    
    .error.error {
      color: white;
      background: red;
      padding: 0.5em;
    }
    
    .container .error {
      background: orange;
    }
    <input type=text value=XYZZY><br>
    <input type=checkbox> XYZZY<br>
    <input type=text class=error value=XYZZY><br>
    <div class=error>XYZZY</div>
    <div class=container><div class=error>XYZZY</div></div>