Search code examples
cssanimationrotationcss-transforms

How can I stop an animation without to reset the spinning rotation in CSS (example explains it best)


I have a little noobish CSS question If someone could share some free time to help. what I want to do is the div to stop and freeze at the position whenever I leave (hover off) my cursor, and not reset to his fixed starting position.

<script>

.rotatingDiv {
width: 50px;
height: 30px;
background-color: red;
margin: auto;
margin-top: 10rem;
cursor: pointer;
}

.rotatingDiv:hover {
animation: spin 4s linear infinite;
}

@keyframes spin {
0% {
 transform: rotate(0deg);
}
100% {
 transform: rotate(360deg);
}
}

</script>


<body>
<div class="rotatingDiv"> </div>
</body> 


as seen on the example the div keeps reseting to the starting position which is 0deg (default) on mouse-out, so what I want to achieve is for the div to freeze at the exact degree whenever I leave my cursor (mouse out/ hover off) from the div.


Solution

  • I think you wanted this thing it would be work

    .rotatingDiv {
        width: 50px;
        height: 30px;
        background-color: red;
        margin: auto;
        margin-top: 10rem;
        cursor: pointer;
        animation: spin 4s linear infinite;
        animation-play-state: paused;
        }
    
        .rotatingDiv:hover {
        animation: spin 4s linear infinite;
        }
    
        @keyframes spin {
        0% {
         transform: rotate(0deg);
        }
        100% {
         transform: rotate(360deg);
        }
        }
    <body>
        <div class="rotatingDiv"> </div>
        </body>