docs/guide/styling.md
This section explains some different ways to style HTML within Marko. From simple inline styles to powerful techniques like CSS Modules for organized and maintainable stylesheets.
Marko enhances the HTML <style> tag to be processed and optimized by the bundler used in the project. A template may specify any number of <style> tags.
By default, all styles defined in the template are globally scoped. As such, many Marko projects use patterns like BEM to avoid name conflicts.
<style>
/* Bundled and loaded once */
.fancy {
color: green;
}
</style>
<div class="fancy">Hello!</div>
The <style> may include a file extension to enable css preprocessors such as scss and less.
<style.scss>
$primary-color: green;
.fancy-scss {
color: $primary-color;
}
</style>
<div class="fancy-scss">Hello!</div>
<style.less>
@primary-color: blue;
.fancy-less {
color: @primary-color;
}
</style>
<div class="fancy-less">Hello!</div>
If the <style> tag has a Tag Variable, it leverages CSS Modules to expose its classes as an object.
<style/styles>
.foo { border: 1px solid red }
.bar { background: green }
</style>
<div class=styles.foo />
<div class=[styles.foo, styles.bar] />
<div class={ [styles.bar]: true } />
<div.${styles.foo} />
This approach allows for scoping of CSS class names without needing to follow naming conventions such as BEM.
You may still provide a custom file extension to enable to use of preprocessors.
<style.scss/styles>
$primary-color: green;
.fancy {
color: $primary-color;
}
</style>
<div class=styles.fancy>Hello</div>
Styling files adjacent a custom tag are automatically discovered. These files are imported and processed the same as inline styles.
/* style.css */
.fancy {
color: green;
}
/* index.marko */
<div class="fancy">Hello!</div>
[!TIP] When a template is becoming too large it can be helpful to pull its styling into an associated style file such as this.
Styles may also be imported.
/* fancy.css */
.fancy {
color: red;
}
/* index.marko */
import "./fancy.css";
<div class="fancy">Hello!</div>
[!TIP] Although generally inline or auto-discovered styles are preferred, importing styles can be helpful when sharing across templates.
CSS Module files may also be imported.
/* something.module.css */
.fancy {
color: red;
}
/* index.marko */
import * as styles from "./something.module.css";
<div class=styles.fancy/>
[!CAUTION] Since most bundlers are configured by default to support css modules for
*.module.cssfiles, this should work out of the box. If it is not supported by a bundler there is almost certainly a plugin.