Home > Mobile >  Apply hover effect in css
Apply hover effect in css

Time:12-06

I have a react js application witch contains a select with a dropdown. I want to apply styles for 2 states: when the mouse hover the dropdown item and when the dropdown item is focused.

.select__option.select__option--is-focused {
  background: blue;
}

.select__option:hover {
  background: gray;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Both styles work. If the user will navigate within dropdown with keyboard arrow (up/down) the will be applied blue color on the item, if he will hover the item will be applied gray color as background.
ISSUE: When user hover the focused item which has blue background, the hover color overrides the blue, but i want to not override blue color even the hover is applied over focused element, so the focused element should keep everytime its color.
How to fix that?
https://codesandbox.io/s/codesandboxer-example-forked-y4zs8?file=/example.tsx:0-505

CodePudding user response:

Just switch elements in place (so that later overwrites previous) or make .select__option.select__option--is-focused:hover{background: blue} as rule too

.select__option:hover {
  background: gray;
}

.select__option.select__option--is-focused {
  background: blue;
}
<div class="select__option">
  .select__option
</div>
<div class="select__option select__option--is-focused">
  .select__option.select__option--is-focused
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If nothing else helps, then just write a rule that does explicitly apply blue background color when both conditions are met - the element has those class names, and is hovered. You can combine both into one single rule, by simply listing both selector expressions comma separated.

.select__option.select__option--is-focused,
.select__option.select__option--is-focused:hover {
  background: blue;
}

CodePudding user response:

Try the not() pseudo class:

.select__option:not(.select__option--is-selected):hover {
  background: gray;
}

My bad, i gave the wrong class in the not(). updated it

  • Related