I have elements with different background-color
s. When a link is clicked, I want to highlight the element with a different color (yellow), then fade back to the element's original color. I know there is currentColor
for an element's color
, but there's nothing similar for background-color
.
How can I smoothly transition from a highlight color back to the element's original background-color
? Right now it fades from the highlight color to transparent, then jumps abruptly back to the original color when the animation ends.
:target td {
animation: highlight 1s;
}
@keyframes highlight {
from {
background-color: yellow;
}
to {
/* How do I set this back to the element's original background-color? */
background-color: transparent;
}
}
<ul>
<li>
<a href="#link1">Link #1</a>
</li>
<li>
<a href="#link2">Link #2</a>
</li>
<li>
<a href="#link3">Link #3</a>
</li>
</ul>
<table>
<tr id="link1">
<td>This is Link #1</td><td>// Fine.</td>
</tr>
<tr id="link2">
<td bgcolor="orange">This is Link #2</td><td>// Ugly.</td>
</tr>
<tr id="link3">
<td bgcolor="red">This is Link #3</td><td>// Ugly.</td>
</tr>
</table>
Just don't include a to
for the animation. This works because if an end (or start) state is not defined, the browser will use the element's existing styles (RE: Valid Keyframe Lists on MDN)
div {
margin: 200px 0;
}
:target td {
animation: highlight 1s;
}
@keyframes highlight {
from {
background-color: yellow;
}
}
<ul>
<li>
<a href="#link1">Link #1</a>
</li>
<li>
<a href="#link2">Link #2</a>
</li>
<li>
<a href="#link3">Link #3</a>
</li>
</ul>
<table>
<tr id="link1">
<td>This is Link #1</td><td>// Fine.</td>
</tr>
<tr id="link2">
<td bgcolor="orange">This is Link #2</td><td>// Ugly.</td>
</tr>
<tr id="link3">
<td bgcolor="red">This is Link #3</td><td>// Ugly.</td>
</tr>
</table>