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

Sleek and versatile sidebar reaching full height

Is there a way to make my sidebar cover the full height of the screen without using position: fixed? The code I've tried doesn't seem quite right. Any tips? JSFindle: http://jsfiddle.net/Pw4FN/57/ if($(window).height() > $('#page-contai ...

What could be the reason for the sudden malfunction of the .tabs li:hover property on my

I'm having trouble with the :hover effect not working on my .tabs li element. I've tried commenting out my jQuery script, but it still won't apply. Can anyone help me figure out why? Here's a JSFiddle link for reference: https://jsfidd ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...

Update Personal Information with PHP and MySQL

i have two files named edit.php and update.php. The content of edit.php is as follows: <?php session_start(); $_SESSION['id'] = '9'; $id = $_SESSION["id"]; $username = $_POST["username"]; $fname = $_POST["fname"]; $password = $_POST ...

Is it possible to trigger a server-side event using jQuery in SharePoint 2010?

For my Sharepoint 2010 application, I have been utilizing jQuery to handle most events on the client-side. However, when it comes to saving data to the Sharepoint list and generating a PDF file with that data, I need to switch to server-side processing usi ...

What is the default method for automatically disabling drop down fields?

I've created a script that will gray out a drop-down field if a prior selection wasn't made. Once the appropriate choice is selected, the grayed-out field will become active. My query is, how can I set the drop-down field to be initially grayed ...

Arrange the element as though it were the foremost

My specific scenario is as follows: <div id="container"> <p id="first">...</p> <p id="second">...</p> </div> I am looking to rearrange the order of second and first within the HTML stru ...

Creating interactive forms (the optimal method)

My project involves creating an Android Tablet application that will connect to a web service to retrieve dynamic forms which can be filled offline and then submitted when online. These forms are not predefined, and may contain attached images. However, I ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

Discovering the selected row with jqueryIs there a way to locate

There is a table with rows and a button that allows you to select a row: <table id="mytable" class="table-striped"> <tbody> <tr id="1"><td>Test1</td></tr> <tr id="2"><td>Test2</td>& ...

Is there a way to adapt my existing navigation bar to collapse on smaller devices?

Struggling to make my navigation bar collapsible on my site designed for a class project. Wondering if this requires both HTML and CSS, or can it be achieved with just HTML since this is my first time working on responsive design. Below is the code I have ...

Leveraging the browser's built-in validation error messages in Angular for HTML forms

Is there a way to incorporate browser's native HTML validation error messages into Angular applications? What I am looking for is the ability to leverage the built-in error messages when working with reactive forms like this: testForm: FormGroup = th ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Sharing a document that contains a linked image file using a relative path through the `publish` feature

I have reviewed the documentation and tested the steps provided in this example, but I am still unable to find a solution for the issue at hand. Based on the documentation, the image file should either be located in the same path as the MATLAB script bein ...

Access a designated tab within a CSS-designed tab system

Can anyone offer some assistance? I currently have a tab structure created using CSS. The first tab is set as the default when the page loads. I am looking to create a link from another page that will take users directly to the page with the tabs and ope ...

A chart using JavaScript that displays text values instead of a traditional website

I am a student with no background in programming, however, for my project I need to create a chart based on values from a txt file to display sensor data. I came across a chart that retrieves its values from a website, but I would like to modify it so it c ...