Search code examples
htmlcssmarkdownhugotoml

How to change Hugo-Coder avatar based on if dark mode is enabled?


Background of environment

  • I am currently building a site in Hugo using the theme Hugo-Coder
  • avatar.png is my current avatar specified in config.toml

Summary of issue

  • In config.toml you can enable dark mode by adding: colorscheme = "auto"
  • This enables dark mode, but my avatar does not show well because it is black

Solution needed

  • I need a way to change avatar.png to avatarDarkMode.png based on if the user's system is set to light or dark mode

Hopefully I added enough information!

Source code repo: GitHub Repo


Solution

  • You might consider a shortcode similar to the one used in onweru/newsroom:

    Picture You want to use darkmode images when darkmode is enabled on a device and a regular image on lightmode? It takes 3 positional parameter

    Store these images in the static/images directory.

    ...
    {{< picture "lightModeImage.png" "darkModeImage.png" "Image alt text" >}}
    ...
    

    It uses layouts/shortcodes/picture.html:

    {{- $normal := .Get 0 }}
    {{- $dark := .Get 1 }}
    {{- $alt := .Get 2 }}
    {{- $normalPath := absURL (printf "images/%s" $normal) }}
    {{- $darkPath := absURL (printf "images/%s" $dark) }}
    <picture class = 'nav_logo'>
      <source srcset = '{{ $darkPath }}' media="(prefers-color-scheme: dark)">
      <img srcset = '{{ $normalPath }}' alt = '{{ $alt }}'>
    </picture>
    

    How about SVG file?
    Is there any way to change the style of an SVG file instead of creating two different SVG image, one for dark mode and one for light mode?

    For SVG, you can try CSS Media Queries:
    You can use CSS media queries to detect whether the user has a light or dark theme enabled in their operating system or browser, and then apply different styles to the SVG accordingly.
    For example:

    @media (prefers-color-scheme: dark) {
       svg {
           filter: invert(1);
       }
    }