Redefining the colors of an SVG when it is a CSS background image in code

I currently have an SVG icon encoded within my CSS file. I'm looking to change the color of this icon when a user hovers over it without creating a duplicate icon in a different color.

Here's a snippet from my CSS file:

background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 511.999 511.999'%3E%3Cpath fill='red' d='M83.578 167.256H16.716C7.524 167.256 0 174.742 0 183.971v300.881c0 9.225 7.491 16.713 16.716 16.713h66.862c9.225 0 16.716-7.489 16.716-16.713V183.971c0-9.229-7.525-16.715-16.716-16.715zM470.266 167.256c-2.692-.456-128.739 0-128.739 0l17.606-48.032c12.148-33.174 4.283-83.827-29.424-101.835-10.975-5.864-26.309-8.809-38.672-5.697-7.09 1.784-13.321 6.478-17.035 12.767-4.271 7.233-3.83 15.676-5.351 23.696-3.857 20.342-13.469 39.683-28.354 54.2-25.952 25.311-106.571 98.331-106.571 98.331v267.45h278.593c37.592.022 62.228-41.958 43.687-74.749 22.101-14.155 29.66-43.97 16.716-66.862 22.102-14.155 29.66-43.97 16.716-66.862 38.134-24.423 25.385-84.871-19.172-92.407z'/%3E%3C/svg%3E");

The icon's color is set to red using the fill='red' attribute.

I am trying to figure out how to change the color to blue on hover, without duplicating the icon and just altering the fill color. Creating another CSS class with the same code but a different fill color seems like an inefficient solution as it would increase the file size unnecessarily.

Answer №1

To change the color of an icon, you can utilize the filter property:

.box {
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 511.999 511.999'%3E%3Cpath fill='red' d='M83.578 167.256H16.716C7...............

}

.box:hover {
  filter: hue-rotate(210deg);
}
<div class="box">

</div>

Another technique is to use the icon as a mask and adjust its color by setting the background-color:

.box {
  -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 511.999 511.99......................

}

.box:hover {
  background: blue;
}
<div class="box">

</div>

You can also experiment with gradient coloring:

.box {
  -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 511.999 51.............

}

.box:hover {
  background: linear-gradient(yellow, green);
}
<div class="box">

</div>

Answer №2

In my solution, I have chosen to utilize data URI encoding with the help of encodeURIComponent(). Despite being encoded, the resulting code remains readable and can be easily manipulated in JavaScript. Specifically, I have created a function called setFill() where I include fill='${color}' within the data URI.

test.addEventListener("mouseover", () => {
  setFill(test, "gold");
});

test.addEventListener("mouseleave", () => {
  setFill(test, "black");
});

function setFill(element, color) {
  element.style.background = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ctitle%3Ethumb up%3C/title%3E%3Cpath d='M0 0h24v24h-24z' fill='none'%3E%3C/path%3E%3Cpath fill='${color}' d='M1 21h4v-12h-4v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06l-1.06-1.05-6.58 6.59c-.37.36-.59.86-.59 1.41v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01.01-.08z'%3E%3C/path%3E%3C/svg%3E")`;
}
#test{
width:50px;
height:50px;
border:1px solid;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ctitle%3Ethumb up%3C/title%3E%3Cpath d='M0 0h24v24h-24z' fill='none'%3E%3C/path%3E%3Cpath d='M1 21h4v-12h-4v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06l-1.06-1.05-6.58 6.59c-.37.36-.59.86-.59 1.41v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01.01-.08z'%3E%3C/path%3E%3C/svg%3E");  
}
<div id="test" ></div>

If you need assistance encoding SVGs using encodeURIComponent(), here is a useful tool: SVG-encoder

Answer №3

I recently discovered a helpful trick that solved my issue.

  1. Start by copying your code from %3Csvg to svg%3E"
  2. Next, navigate to
  3. Paste your code in the URL-encoded section and in the area above that, replace the fill field with your desired color in HEX format.
  4. Locate your color in encoded format within the Url-encoded section surrounded by %27. For instance, '#ff9500' <=> %27%23ff9500%27, thus #ff9500 <=> %23ff9500.
  5. Finally, copy this encoded color into your code and it should work perfectly! Feel free to reach out if you encounter any issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to move content without affecting the background of the `<body>` using scrolling

Can I achieve a glass morphism effect on my page without moving the background of the body? I only want to move the .container. Is this feasible? I attempted using background-attachment: fixed, but it did not work for me. Here is the code snippet I have be ...

Dynamically switch between doubling Ajax calls in JavaScript

Encountering an issue with a jQuery click function. Triggering the click event on an HTML button dynamically loads styled checkbox and toggle switches based on their stored on/off state in a database. An additional click function is added to each loaded t ...

Opening Tags in Selenium for HTML

Is it possible for Selenium with XPath to properly work with HTML that is not in the form of XML, and contains open tags like <col> and <input>? I'm curious if anyone can confirm this. I ask because our automation testing team has noticed ...

Eliminating the gray background using CSS

How can I remove the gray background that automatically appears in my CSS header? .header { padding: 60px; margin: 20px auto auto auto; width: 1400px; border-radius: 10px; text-align: center; background: # ...

Changing the color of HTML text based on a variable in Vue JS can be achieved by altering the CSS styles dynamically

I have developed a website that shows values with a set threshold. I now want to change the color of the values when they exceed the threshold, but I am unsure of how to proceed. I want to display consultation.indicateurs.TRS in red when it exceeds the va ...

What is the reason behind receiving a CSS warning stating "Expected color but found '0' " when using Phaser's setText() function?

Here's how I created my text object: statusBarHP.text = game.add.text(0, 0, '', { font:"16px Arial", fill:"#ffffff", stroke:"#000000", strokeThickness:2 }); For the object that holds the text: statusBarHP = game.add.sprite ...

Guide on triggering CSS @keyframes animations upon element visibility while scrolling

I'm struggling with controlling CSS animations that I want to start only when the element becomes visible on the screen. The issue arises because I have a website with a total height of around 8000px and the element with the animation is located far d ...

PHP SQL bug causing incorrect username displays

This logon script is functioning well on my website: <?php include 'pdo_connect.php'; if(!empty($_POST)) { $query = "SELECT `password` FROM `users` WHERE `uname` = ?"; $params = array($_POST['uname']); $results = data ...

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

Design a CreateJS/EaselJS website, comprised of multiple web pages, that is not focused on gaming

I have developed an existing HTML5 Canvas webpage composed of multiple pages, buttons, and hotspots using pure canvas javascript code. The reason I refer to 'buttons' and 'hotspots' in quotes is because I created them from scratch in j ...

The lobster custom font is malfunctioning in Internet Explorer

I am trying to use the unique font called lobster. After downloading the lobster.woff2 file, I stored it in the font folder. In my custom CSS, I added the following: @font-face { font-family: 'Lobster'; font-style: normal; font-weight: 40 ...

Changing CSS module variables through JavaScript programming

I'm currently utilizing an older version of react-boilerplate that includes CSS Modules, allowing for the creation of variables and the ability to import them into other CSS files. Below is my colors.css file: :root { /* Status colors */ --error ...

Display the element only when the request sent with getJSON exceeds a certain threshold of time in milliseconds

Here's a snippet of my JavaScript code: surveyBusy.show(); $.getJSON(apiUrl + '/' + id) .done(function (data) { ... surveyBusy.hide(); }) .fail(function (jqXHR, textStatus, err) { ... surveyBusy. ...

What is the best way to implement dragging functionality for an image within a specific area?

Here's a snippet of the code I'm working with: link This is the HTML code: <div class="border"> <div id="i-choose"> <input type="file" name="file" id="file" class="inputfile"> <label for="file"& ...

What could be the reason for the lower section of my website not being displayed?

I'm having an issue with a new div I added to the bottom half of my website - it's not showing up. Oddly enough, when I test the same code on a separate web page, it works fine. Can someone please take a look at the code and help me out? Thank yo ...

Looking to update properties for elements within the Angular Material 16 mat-menu across the board?

Currently working with Angular Material 16 and I have a question regarding the height of buttons inside the mat-menu element. Here is an example of the code: <button mat-icon-button> <mat-icon>more_vert</mat-icon> </button> ...

Ways to position Bootstrap 4 navbar elements at the bottom

Struggling to adjust the alignment of the text in the navbar items using Bootstrap 4? My initial thought was to align them at the bottom of the ul and then position the ul accordingly, but I'm facing challenges with both. The objective is to have the ...

Floating action buttons in CSS

I'm trying to create a button that reveals additional options when hovered over. I've been looking for a method similar to what's shown in the image below, but haven't been successful. This needs to be implemented on a web page using HT ...

How to position an image on top of each printed page using HTML/CSS (SCSS)

I've created a simple and small webpage that looks like this: Everything is perfect in the browser, with all the styles (margin, padding, etc.) just as I want it. However, my issue lies in the print view of the page. As shown in the image above, th ...

Having difficulty connecting images or photos to CodePen

I've been attempting to connect images and sound files to my CodePen project using a Dropbox shared link. <div class="container"> <div class="row second-line"> <div class="col-12"> <div d ...