How to Make a Themeable SVG Favicon

Blog

Posted by Nuno Marques on 23 Oct 2022

Hey there, web developers! Today, we’re diving into a fun little project: creating a themeable SVG favicon. This will help your website adapt to light and dark modes effortlessly. Plus, using SVG means your favicon will look crisp at any size! Let’s get started.

What You’ll Need

Before we jump into the code, make sure you have:

  • A basic understanding of HTML and CSS.
  • A text editor to write your code.

Step 1: Create Your SVG

First, we need an SVG file. Here’s a simple example you can use. This SVG includes styles that adapt to the user’s color scheme:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   viewBox="0 0 782 782" style="enable-background:new 0 0 782 782;" xml:space="preserve">
  <style>
    @media (prefers-color-scheme: dark) {
      path { fill: #fff; }
    }
    @media (prefers-color-scheme: light) {
      path { fill: #000; }
    }
  </style>
  <path d="M-4157-9489.8c-5.3-109.6-81.6-211.5-186.1-245.8c-5.3-1.7-10.7,2.2-10.7,7.8l0.3,58.2
    c0,6.2,3.4,11.8,8.7,14.8c27.2,15.2,48.4,41.6,61.4,69.6c52.1,111.6-45.4,240.9-166.4,223.6h0c-148-21.1-188.8-219.5-62.3-295.1
    c5.1-3,8.2-8.4,8.4-14.3l1.4-55.7c0.1-5.6-5.4-9.7-10.7-8c-171,57-240.2,264-140.4,415.2
    C-4491.4-9082.2-4141.5-9205.2-4157-9489.8z"/>
</svg>

Step 2: How It Works

The magic happens in the <style> section. We’re using CSS media queries to adjust the fill color of the SVG path based on the user’s preferred color scheme:

  • Dark Mode: When the user prefers a dark theme, the path fills with white.
  • Light Mode: In light mode, it fills with black. This ensures your favicon looks great in both themes!

Step 3: Add the Favicon to Your HTML

Next, we need to link this SVG as a favicon in your HTML file. Here’s how you can do that:

!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Themeable SVG Favicon</title>
    <link rel="icon" type="image/svg+xml" href="path/to/your/favicon.svg">
</head>
<body>
    <h1>Welcome to My Website!</h1>
</body>
</html>

Replace path/to/your/favicon.svg with the actual path where you saved your SVG file.

Step 4: Test It Out

To see your themeable favicon in action:

  1. Open your browser and load your HTML page.
  2. Switch between light and dark modes on your operating system or browser settings to see the favicon adapt.

Wrapping Up

And there you have it! A simple yet effective way to create a themeable SVG favicon for your website. This not only enhances user experience but also keeps your site looking sharp and modern.

Feel free to experiment with different SVG shapes and colors to match your brand’s style. Happy coding, and don’t hesitate to reach out if you have any questions!