【问题标题】:SASS/SCSS - Color switch on body doesn't workSASS/SCSS - 身体上的颜色开关不起作用
【发布时间】:2021-01-31 15:30:45
【问题描述】:

我想用 SASS 预处理器在 CSS 中构建一个简单的主题颜色切换器。例如,当我单击按钮时,背景颜色会从白色变为黑色/黑色变为白色。该功能适用​​于我的 div 按钮,但不适用于我的身体(设置了背景颜色)。你知道为什么吗?

谢谢

HTML

<body>
    <div class="container">
        <button class="toggle-btn">Toggle theme</button>
    </div>
</body>

CSS/SCSS

*,
*::before,
*::after {
    margin: 0;
    padding: 0;
    box-sizing: inherit;
}

:root {
    font-size: 14px;
}

body {
    box-sizing: border-box;

    min-height: 100vh;

    display: flex;
    justify-content: center;
    align-items: center;

    .dark-theme & {
        background-color: black;
    }
}

.container {
    border: 2px solid red;

    height: 500px;
    width: 1000px;

    display: flex;
    justify-content: center;
    align-items: center;

    transition: all .3s;

    .dark-theme & {
        background-color: black;
    }
}

.toggle-btn {
    background-color: black;
    color: white;
    padding: 15px;

    .dark-theme & {
        background-color: white;
        color: black;
    }
}

JS

const toggleBtn = document.querySelector('.toggle-btn');

toggleBtn.addEventListener('click', () => document.body.classList.toggle('dark-theme'));

code

【问题讨论】:

    标签: css sass


    【解决方案1】:

    你正在写作

    body {
        .dark-theme & {
            background-color: black;
           }
        }
    

    表示body元素的暗主题类名inside。更改为&amp;.dark-theme,其中&amp; 表示within 正文元素。

    body {
     &.dark-theme {
            background-color: black;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-23
      • 2016-04-14
      • 2014-12-07
      • 2020-03-21
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多