How to Fill an LI Element\'s Background Color from Left to Right on Hover with CSS3?

Susan Sarandon
Release: 2024-10-30 12:58:26
Original
999 people have browsed it

How to Fill an LI Element's Background Color from Left to Right on Hover with CSS3?

Filling Background Color Left to Right with CSS

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>
Copy after login

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>
Copy after login

Demo:

<code class="html"><li>Hover me to fill the background</li></code>
Copy after login
<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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!