SVG Color Change on Hover
January 31, 2025 ยท AI Conversations
—
### **1. Using CSS (`fill` or `stroke`)**
If the SVG is embedded directly in the HTML (“ tag), you can target its `fill` or `stroke` in CSS.
#### **Example: Change `fill` on Hover**
<svg width="100" height="100" viewBox="0 0 24 24" class="icon">
<path d="M12 2L2 22h20L12 2z" fill="black"/>
</svg>
<style>
.icon:hover path {
fill: red; /* Change color on hover */
}
</style>
#### **Example: Change `stroke` on Hover**
<svg width="100" height="100" viewBox="0 0 24 24" class="icon" stroke-width="2">
<path d="M12 2L2 22h20L12 2z" fill="none" stroke="black"/>
</svg>
<style>
.icon:hover path {
stroke: red; /* Change stroke color on hover */
}
</style>
—
### **2. Using `currentColor` for Dynamic Changes**
If you set `fill="currentColor"`, the SVG will inherit the `color` from CSS.
<svg width="100" height="100" viewBox="0 0 24 24" class="icon">
<path d="M12 2L2 22h20L12 2z" fill="currentColor"/>
</svg>
<style>
.icon {
color: black; /* Default color */
}
.icon:hover {
color: red; /* Change color on hover */
}
</style>
—
### **3. Changing Color for an External SVG File (“ or `background-image`)**
If your SVG is in an “ tag or `background-image`, you **cannot** change its color with CSS. Instead, you need to:
– Use an **inline SVG**.
– Apply a **CSS filter** (not always precise).
– Use **JavaScript** to swap the image.
#### **Example: Using `filter` for “ SVGs**
img.icon {
filter: brightness(0) saturate(100%) invert(0%) sepia(0%) saturate(7500%) hue-rotate(0deg);
transition: filter 0.3s ease;
}
img.icon:hover {
filter: brightness(0) saturate(100%) invert(20%) sepia(90%) saturate(5000%) hue-rotate(360deg);
}
#### **Example: Swapping Image with JavaScript**
<img src="icon-black.svg" id="myIcon" width="100">
<script>
document.getElementById("myIcon").addEventListener("mouseover", function() {
this.src = "icon-red.svg";
});
document.getElementById("myIcon").addEventListener("mouseout", function() {
this.src = "icon-black.svg";
});
</script>
—
Which method works best for your project setup? ๐