fbpx
date icon July 15, 2024

How can I change the colour of an ‘svg’ element?

CEO & Founder at CodeOp

If you have been to our full-stack development course, you’ll know how much I adore SVGs – as any developer would.

Unlike traditional image formats, SVGs aren’t rasterised but vector-based, meaning they can scale indefinitely without losing quality. This makes SVG format ideal for responsive design across different devices and screen aspect ratios.

When I first started out in my coding journey, I treated SVGs as just better PNGs, meaning I could scale them without any problem.

However, it’s best to not treat them as images. With just a few lines of code, you can change the fill-colour, stroke lines and various other attributes of your SVGs.

Colour Properties of SVG:

  • The fill property defines the colour inside the vector shapes.
  • The stroke property defines the colour of the outline of the SVG shape.

Here’s a quick snippet of code demonstrating how easy it is to change the colour of your SVG element using CSS:

/* CSS to style an SVG circle with class 'my-circle' */

.my-circle {

fill: #ff6347; /* tomato red */

stroke: #2e8b57; /* sea green */

stroke-width: 3px;

}

While the snippet above may do your job now, there are five ways to change the colour of your SVG element. And as a responsible developer, you should know all of them.

Changing the Colour of SVG Elements

1. Inline CSS

In this, we’ll place the CSS directly within the SVG element’s opening tag in the HTML document. It’ll let you apply styles to the SVG quickly and directly without affecting other elements.

Example:

<svg height="100" width="100">

<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" style="fill: blue;" />

</svg>

In this example, the style attribute is used within the <circle> element to change its fill colour to blue. It’ll override any other colour specified by other CSS rules for the fill property.

2. Internal CSS

For internal CSS, we’ll embed a <style> block directly within the SVG file. This method is particularly useful if your SVGs are stored as standalone files.

Example: Here’s how you might encapsulate CSS within an SVG:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">

<style>

.myCircle { fill: green; stroke: yellow; stroke-width: 4; }

</style>

<circle cx="50" cy="50" r="40" class="myCircle" />

</svg>

In this SVG, the <style> block defines the styles for elements with the class circle. This circle will have a green fill and a yellow stroke wherever this SVG is embedded.

3. External CSS

This is probably the method you’re trying to use as a web developer – using an external stylesheet. With this approach, you’ll keep your HTML or SVG markup clean and separate the concerns of styling and structure.

Example:

<svg class="mySvgIcon">

<use xlink:href="icon.svg#icon-graphic"></use>

</svg>

You can then style it from an external CSS file like so:

.mySvgIcon {

fill: purple;

stroke: orange;

stroke-width: 2;

}

This CSS will apply the styles to any SVG element with the class mySvgIcon, changing the fill to purple and the stroke to orange. It is highly efficient for managing styles across multiple SVG elements.

4. Using Plain JavaScript

Plain JavaScript can be directly used to manipulate the DOM properties of an SVG element. This method is particularly useful for dynamic interactions and real-time updates to your image files based on user actions or other conditions.

Example:

<body>

<script src="https://d3js.org/d3.v6.min.js"></script>

<script>

const data = [12, 31, 22, 17, 25, 18, 29, 14, 9];

const svg = d3.select("body").append("svg")

.attr("width", 500)

.attr("height", 100);

svg.selectAll("rect")

.data(data)

.enter()

.append("rect")

.attr("x", (d, i) => i * 30)

.attr("y", (d) => 100 - 3 * d)

.attr("width", 25)

.attr("height", (d) => 3 * d)

.attr("fill", "navy");

</script>

</body>

5. Using JavaScript Libraries (e.g., D3.js)

JavaScript libraries like D3.js are designed to handle data-driven transformations and visualize complex data sets. It does so by binding data to the DOM and applying transformations to the presentation.

D3.js extends beyond mere colour changes, allowing you to create complex, responsive visualizations that dynamically update and interact with large datasets.

Example:

<svg width="100" height="100">

<circle id="myCircle" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"/>

</svg>

<button onclick="changeColor()">Change Color</button>

<script>

function changeColor() {

document.getElementById('myCircle').setAttribute('fill', 'blue');

}

</script>

This snippet creates a simple bar chart by binding an array of numbers to rect elements within an SVG. The data determines each rectangle’s height and position, and the colour is set to navy.

D3.js handles the creation and positioning based on the data, demonstrating its capability to generate dynamic visual content.

Best Practices When Handling SVG Elements

1. Performance

When implementing dynamic colour changes for SVGs, you must consider the impact on performance. Inline and internal CSS methods generally have minimal impact because they render quickly.

However, using JavaScript, especially with complex libraries like D3.js, can affect performance if not managed carefully. Large datasets or frequent updates can significantly increase load times and render delays.

To mitigate this, you should optimise your data handling and limit the frequency of DOM element updates.

You can review your progress using Google’s PageSpeed Tool.

2. Accessibility

Ensure that the colour contrasts meet the WCAG (Web Content Accessibility Guidelines) standards, especially when colour changes convey important information or actions.

Always provide additional cues, such as text labels or patterns, to ensure all users can fully interact with and understand your website’s content.

Additionally, when using JavaScript to manipulate SVGs, ensure the changes do not disrupt screen readers or keyboard navigation.

Proper ARIA (Accessible Rich Internet Applications) attributes should be used to describe any changes in the state or purpose of SVG elements due to colour changes.

And this was JUST changing colours. There’s a lot more you can do with SVG elements. aspose.com has great documentation on SVG elements if you wish to read through some white paper.

Author: Katrina Walker
CEO & Founder of CodeOp,
An International Tech School for Women, Trans and Nonbinary People
Originally from the San Francisco Bay Area, I relocated to South Europe in 2016 to explore the growing tech scene from a data science perspective. After working as a data scientist in both the public...
More from Katrina →