Home > Article > Web Front-end > How to Fill an LI Element\'s Background Color from Left to Right on Hover with CSS3?
Q: I'm trying to create an effect where the background color of an li element fills from left to right upon hover. How can I achieve this using CSS3?
A: Utilize a linear gradient as the element's background and animate its position. Here's the code:
<code class="css">/* Set up the background gradient (red to blue) */ background: linear-gradient(to left, red 50%, blue 50%) right; /* Make the background twice the size of the element */ background-size: 200% 100%; /* Position the background to the right */ background-position: right;</code>
On hover, change the background position to the left to fill the element. You can add a smooth transition by using transition: all 2s ease;.
<code class="css">/* On hover, change the background position to the left */ background-position: left;</code>
Demo:
<code class="html"><li>Hover me to fill the background</li></code>
<code class="css">li { display: inline-block; padding: 1em; background: linear-gradient(to left, red 50%, blue 50%) right; background-size: 200% 100%; background-position: right; transition: all 2s ease; } li:hover { background-position: left; }</code>
The above is the detailed content of How to Fill an LI Element\'s Background Color from Left to Right on Hover with CSS3?. For more information, please follow other related articles on the PHP Chinese website!