0

I am trying to provide multiple themes for web site. I know how to use sass. As far as I understand, the steps are like followings.

  1. creating sass file.
  2. sass file is pre-processed.
  3. the corresponding css file is created

That means that the css file is already properly written (either through sass or direct css) and used in html file. But the way I want to implement is that there is a option box allowing users to use theme. Whatever theme a user clicks, the newly selected theme is immediately applied in html page. How I can achieve this by using sass? Could you give me some concept about it if you have this kind of experience?

Anna Lee
  • 909
  • 1
  • 17
  • 37

2 Answers2

3

There are a few different ways, but one option is to have parent classes for each of the themes to house the styles specific to those themes.

For example, SCSS:

.dark-theme {
    .content {
        background: #333;
        color: #fff;
    }
}

.light-theme {
    .content {
        background: #eee;
        color: #333;
    }
}

And then when your user selects a theme, you can use javascript to change the class on a top-level element, such as the body:

HTML:

<body class="dark-theme">
    ...
</body>

JS: See this answer for how to change a classname with javascript.

miir
  • 1,814
  • 1
  • 17
  • 25
  • 1
    Ah, it seems simple and clear. I will try it. Thank you so much!! – Anna Lee Oct 22 '18 at 23:53
  • I am really sorry for late response. I have a question. The scss file also has to be converted into css file and then the converted css file is linked in the html file? – Anna Lee Oct 25 '18 at 00:58
  • Correct, if you want to write your css styles using Sass, you must convert it to css for the browser to be able to load it. Then in the html, you can include the "external stylesheet" in the head tag `` – miir Oct 25 '18 at 17:16
0

You can use CSS variables. Doesn't work on IE =( But so amazing!

/* Common css */
p {
  color: var(--color);
  font-size: var(--font-size);
  font-family: var(--font-family);
}
<p>Property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.</p>

<!--Theme A variables-->
<style>
  :root {
    --color: red;
    --font-size: 20px;
    --font-family: sans-serif;
  }
</style>

<!--Theme B variables-->
<!--style>
  :root {
    --color: green;
    --font-size: 14px;
    --font-family: serif;
  }
</style-->
3rdthemagical
  • 5,271
  • 18
  • 36