skip to Main Content

I’ve got the following scenario:

HTML

.input {
  color: red;
}

.input:not(:disabled, :read-only):hover {
  color: blue;
}
<input class="input" type="text" value="Hello">
<div class="input">Hello</div>

So the hover effect won’t apply to the div element, but if I remove the :read-only pseudo-class part from the css, it will.

Why is this happening? 🤔

3

Answers


  1. Because the read-only selector doesn’t just select elements, it will select any element that cannot be edited by the user. This includes that div element.

    @TemaniAfif provides a nice way to make the div editable to make it supports read-only and disable attributes, if you don’t want to make it editable for some reason, you can use classes instead.

    .input {
      color: red;
    }
    
    input.input:not(:disabled, :read-only):hover, .input:not(input):not(.disabled, .read-only):hover {
      color: blue;
    }
    <input class="input" type="text" value="My Input">
    <input class="input" disabled type="text" value="My Disabled Input">
    <div class="input">My div</div>
    <div class="input disabled">My Disabled div</div>
    <div class="input read-only">My read-only div</div>
    Login or Signup to reply.
  2. The :not() pseudo-selector does not take 2 delecrations the way you intend too. Simply use 2 complete selectors.

    .input {
      color: red;
    }
    
    .input:not(:disabled):hover,
    .input:not(:read-only):hover {
      color: blue;
    }
    <input class="input" type="text" value="Hello">
    <div class="input">Hello</div>
    Login or Signup to reply.
  3. The :not() selector you are using is applying an AND logic so both requirements need to be true. :not(:disabled) and :not(:read-only). The div doesn’t match the second one (only the input does) so the hover effect won’t work.

    If you make it editable it will be like the input

    .input {
      color: red;
    }
    
    .input:not(:disabled, :read-only):hover {
      color: blue;
    }
    <input class="input" type="text" value="Hello">
    <div class="input" contenteditable>Hello</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search