Home > Article > Web Front-end > Detailed explanation of the use of hover selector in CSS
Sometimes you need to use the two mouse events mouseover and mouseout, but writing js is more troublesome, and you have to add listening events, so things that can be solved with css should be solved with css as much as possible, which can improve performance. Let me talk about it below. Understanding of :hover:
When we were learning computer applications, the teacher taught us to use the :hover selector to complete the drop-down menu. Before, I only knew how to use it, but I didn’t know why it was used in this way. Now write down how to use it
Definition and usage
Definition:
:hover selector is used to select the element on which the mouse pointer is floating.
:hover selector applies to all elements
Usage 1:
This means: when the mouse is hovering over the style a, the background color of a is set For yellow
a:hover { background-color:yellow; }
This is the most common usage, it just changes the style through a
Usage 2:
Use a to control the style of other blocks:
Use a to control the sub-element b of a:
.a:hover .b { background-color:blue; }
Use a to control a's sibling element c (sibling element):
.a:hover + .c { color:red; }
Use a controls the nearest element d of a:
.a:hover ~ .d { color:pink; }
##To summarize:
1. Add nothing in the middle to control child elements;2. '+' controls sibling elements (sibling elements);
3. '~' controls nearby elements;
Example
Use a button to control the movement state of a box. When the mouse moves over the button, the box stops moving. When the mouse moves away, the box continues to move. body code:<body> <p class="btn stop">stop</p> <p class="animation"></p> </body>
##
<style> .animation { width: 100px; height: 100px; background-color: pink; margin: 100px auto; animation: move 2s infinite alternate; -webkit-animation: move 2s infinite alternate; } @keyframes move { 0% { transform: translate(-100px, 0); } 100% { transform: translate(100px, 0); } } .btn { padding: 20px 50px; background-color: pink; color: white; display: inline-block; } .stop:hover ~ .animation { -webkit-animation-play-state: paused; animation-play-state: paused; } </style>
implementation Effect:
Related recommendations:
The above is the detailed content of Detailed explanation of the use of hover selector in CSS. For more information, please follow other related articles on the PHP Chinese website!