There are a couple of approaches to achieve this. Both involve the use of mixins.
meta.load-css
The sass:meta
functionality allows you to accomplish your goal.
Suppose you have the following scss file with a theme:
//theme/_code.scss
$border-contrast: false !default;
code {
background-color: #6b717f;
color: #d2e1dd;
@if $border-contrast {
border-color: #dadbdf;
}
}
You can import that code into another scss file like this:
// other-theme.scss
@use "sass:meta";
body.dark {
@include meta.load-css("theme/code",
$with: ("border-contrast": true));
}
As a result, the css will look like this:
body.dark code {
background-color: #6b717f;
color: #d2e1dd;
border-color: #dadbdf;
}
For more information on this feature, refer to the documentation.
old fashioned mixin
Alternatively, you can achieve the same outcome using mixins and includes.
Let's say you have a class that you want to include in another class:
.title {
font-size: 2em;
font-weight: bold;
}
And another sass file with a different theme:
.dark-theme {
.title {
font-size: 2em;
font-weight: bold;
color: white;
}
}
You can create a scss mixin and import it into both files:
mixin.scss
@mixin shared-items() {
.title {
font-size: 2em;
font-weight: bold;
}
}
Then, in the theme files:
white-theme.scss
@import './mixin.scss';
/* included as is without a parent class */
@include shared-items;
dark-theme.scss
@import './mixin.scss';
/* included inside the dark-theme class */
.dark-theme {
.title {
color: white;
}
@include shared-items;
}
This will generate the following css:
.title {
font-size: 2em;
font-weight: bold;
}
.dark-theme {
.title { color: white; }
.title {
font-size: 2em;
font-weight: bold;
}
}
Note that you can also pass parameters to mixins and use them as functions.
This allows you to easily pass colors and utilize them with your theme variables.
For example:
/* an example of assigning a color to a placeholder mixin: */
@mixin nk-placeholder($color: #C4C4CC) {
&::-webkit-input-placeholder {
color: $color;
font: inherit;
}
&::-moz-placeholder {
color: $color;
font: inherit;
}
&:-ms-input-placeholder {
color: $color;
font: inherit;
}
&:-moz-placeholder {
color: $color;
font: inherit;
}
&::placeholder {
color: $color;
font: inherit;
}
}
/* similar concept as above */
@mixin shared-items($text-color: black) {
.title {
font-size: 2em;
font-weight: bold;
color: $text-color;
}
}
.white-theme {
@include shared-items;
}
.dark-theme {
@include shared-items(white);
}