Skip to content

RodrigoTomeES/prefers-color-scheme-hack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Prefers Color Scheme Hack 🌗

Header of prefers color scheme hack

The prefers-color-scheme is a CSS media feature, it is used to detect if the user has requested a light or dark color theme. This feature only can be used in <style> tag or in js but Github doesn't allow it in READMEs to prevent attacks.

For this reason I searched for a workaround and I found an article of Chris Coyier in CSS Tricks that talk about add custom CSS in a SVG file. With this idea in mind I supposed that it would be possible to use the prefers-color-scheme media feature with this trick, and it worked! 🚀

Example

I think the best way to see it is with an example, so let's go:

<svg width="200" height="200" viewBox="0 0 200 200" fill="none" xmlns="http://www.w3.org/2000/svg">
    <foreignObject width="100%" height="100%">
        <div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; height: 100%;">
            <style>
                .example {
                    width: 250px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background: #EEEEEE;
                    color: black;
                    font-family: sans-serif;
                    font-size: 25px;
                    text-align: center;
                    padding: 15px;
                }

                .example::after {
                    content: 'You are using a light theme';
                }

                @media (prefers-color-scheme: dark) {
                    .example {
                        background: #323232;
                        color: white;
                    }

                    .example::after {
                        content: 'Welcome to the dark side';
                    }
                }
            </style>
            <div class="example"></div>
        </div>
    </foreignObject>
</svg>

Result

Example of use prefers color scheme

Advanced use

This tecnic for use prefers color scheme can be use in proyect like github-readme-activity-graph and you can get a stat image that can change with your them browser preferences. In the case of the github-readme-activity-graph project, I have made an example implementation that you can find here.

Example

Example of advanced use

Limitations

Using prefers color scheme doesn't work as expected in Github apps (android / ios) because they always return the light theme. I don't know if this is a bug of the app or it isn't compatible with this feature.

Resources Used

About

This repository explain Github hack for use Prefers Color Scheme

Topics

Resources

License

Stars

Watchers

Forks