美文网首页
TailwindCSS - 浅色/深色模式

TailwindCSS - 浅色/深色模式

作者: Anoyi | 来源:发表于2022-06-09 14:01 被阅读0次

    追随系统

    Tailwind 使用 dark 变量来定义深色样式(默认浅色),默认情况下,是使用 CSS 媒体查询 prefers-color-scheme 来识别系统模式并展示具体样式,示例代码:

    <html>
    
    <head>
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    
    <body>
        <div class="h-screen w-screen flex justify-center items-center bg-gray-100 gap-16">
            <div class="bg-white w-72 p-10 rounded-lg shadow-lg flex flex-col items-center justify-center dark:bg-slate-800">
                <div class="flex flex-col items-center justify-center gap-4">
                    <img class="w-32 h-32 rounded-full"
                        src="https://upload.jianshu.io/users/upload_avatars/3424642/abb0b8e9-cfb6-40a4-92d1-4e326aeebd32.jpeg?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240"
                        alt="">
                    <div class="text-xl font-medium dark:text-white">Anoyi 🐬</div>
                    <div class="text-sm text-gray-400">追随系统</div>
                </div>
            </div>
        </div>
    </body>
    
    </html>
    

    动态切换

    要支持用户手动切换浅色/深色模式,需要将 Tailwind 的 darkMode 设置为 class 而不是默认的 media,代码示例:

    <html>
    
    <head>
        <script src="https://cdn.tailwindcss.com"></script>
        <script>
            tailwind.config = {
                darkMode: 'class'
            }
        </script>
    </head>
    
    <body>
    </body>
    
    </html>
    

    配置完毕后,开启深色模式,只需给 html 标签的 class 属性加上值 dark 即可,代码如下:

    <!-- 未开启深色模式 -->
    <html>
    <body>
      <!-- 白色背景-->
      <div class="bg-white dark:bg-black">
        <!-- ... -->
      </div>
    </body>
    </html>
    
    <!-- 开启深色模式 -->
    <html class="dark">
    <body>
      <!-- 黑色背景 -->
      <div class="bg-white dark:bg-black">
        <!-- ... -->
      </div>
    </body>
    </html>
    

    因此,使用简单的 JS 代码即可实现浅色/深色模式的切换,代码如下:

    // 页面加载后,设置主题样式
    if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
    
    // 选择浅色模式
    localStorage.theme = 'light'
    
    // 选择深色模式
    localStorage.theme = 'dark'
    
    // 选择追随系统
    localStorage.removeItem('theme')
    

    相关文章

      网友评论

          本文标题:TailwindCSS - 浅色/深色模式

          本文链接:https://www.haomeiwen.com/subject/ndoumrtx.html