简体   繁体   中英

Apply hover effect in css

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

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

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM