Scope your component styles and never worry about a collision ever again.
const greeting = "hello world";
<template>
<div>{{greeting}}</div>
<style scoped>
div {
color: blue;
}
</style>
</template>becomes the equivelent of;
import './abcd1234.css'; // containing your CSS, but with selectors scoped
const greeting = "hello world";
<template>
<div class="abcd1234">{{greeting}}</div>
</template>This is a build-time-only addon, so there is no need to worry about runtime performance.
You can also write your styles as a co-located .css file, right next to your .gjs/.gts files.
Every selector you write in your styles is automatically scoped to the component.
So you can develop your component with styles isolated from the rest of the application and you don't have to worry about CSS selectors collisions or issues with the CSS cascade.
See Usage for details.
If you want to read more specifics on how this addon achieves isolation with CSS you can read more in the detailed CSS isolation documentation
As selectors are scoped/renamed during the build process. So there is no performance hit when running the app.
The philosophy of ember-scoped-css is to stick as close to CSS and HTML as possible and not introduce new syntax or concepts unless it is absolutely necessary.
You may also find the docs on CSS @layer interesting.
This build tool can emit CSS in a @layer.
- Vite
- V2 addons with
@embroider/addon-dev@ v8+ (or similar) - V2 addons / libraries built with rolldown or tsdown (e.g. via
@nullvoxpopuli/ember-rolldown) - For hbs, broccoli, or webpack-based builds, view this version of the docs
| You Have | ember-scoped-css | ember-scoped-css-compat | docs |
|---|---|---|---|
| vite | >= 1.0.0 | 🚫 | main |
| gjs / gts library (no hbs) | >= 1.0.0 | 🚫 | main |
| rolldown / tsdown | >= 3.1.0 | 🚫 | main |
| webpack | <= 0.24.3 | <= 10.0.0 | 0.24.3 |
| hbs | <= 0.24.3 | <= 10.0.0 | 0.24.3 |
| ember-template-imports@v4 or babel-plugin-ember-template-compilation@2.2.5+ | 0.19.0 | 10.0.0 | 0.19 - 0.24 |
| ember-template-imports@v3 or babel-plugin-ember-template-compilation@2.2.1 or rollup-plugin-glimmer-template-tag | <= 0.18.0 | <= 9.0.0 | 0.18 |
| classic components | <= 0.18.0 | <= 8.0.0 | 0.18 |
| ember < 4 | <= 0.18.0 | <= 8.0.0 | 0.18 |
npm install --save-dev ember-scoped-cssConfiguration happens in multiple locations to take over the need portion of your build steps.
vite.config.*rollup.config.*(orrolldown.config.*/tsdown.config.*)babel.config.*
In your vite.config.*, import and add the scopedCSS plugin:
import { defineConfig } from 'vite';
import { scopedCSS } from 'ember-scoped-css/vite';
export default defineConfig({
// ...
plugins: [
scopedCSS(),
// ...
],
});notes for vite projects
If you're import.meta.globing large chunks of your codebase, you'll want to make sure that your globs exclude CSS files
For example:
❌ Don't do this
...import.meta.glob('./templates/**/*', { eager: true })✅ Do this
...import.meta.glob('./templates/**/*.{gjs,gts}', { eager: true }),or better yet, for small projects:
...import.meta.glob('./templates/{top,level,folders}/{sub,folders}.{gjs,gts}', { eager: true }),This way you don't import CSS yourself, which would make CSS go through Vite's default CSS processing. We need the scoped-css plugins to process the CSS instead of Vite's default behaviors.
layerName: string- Wrap your CSS in a@layerwith this given name
If you have a rollup config:
import { scopedCSS } from 'ember-scoped-css/rollup';
// ...
plugins: [
scopedCSS(),
]layerName: string- Wrap your CSS in a@layerwith this given name
The rollup plugin also works under rolldown and tsdown.
For a v2 library built with tsdown via @nullvoxpopuli/ember-rolldown,
the whole setup lives in tsdown.config.js — no babel.config.js needed:
import { defineConfig } from 'tsdown';
import { ember } from '@nullvoxpopuli/ember-rolldown';
import { scopedCSS } from 'ember-scoped-css/rollup';
import { scopedCSS as scopedCssBabel } from 'ember-scoped-css/babel';
export default defineConfig({
entry: ['./src/index.ts'],
css: { inject: true },
plugins: [
ember({
babel: {
// only needed if you use scopedClass in module code
plugins: [scopedCssBabel()],
templateTransforms: [scopedCssBabel.template({})],
},
}),
scopedCSS(),
],
});Notes:
@tsdown/cssmust be installed (it releases in lockstep with tsdown) — it bundles the scoped CSS intodist/style.css.css: { inject: true }keeps theimport './style.css'statement in the built JS, so consuming apps load the CSS through the module graph. Without it the CSS is emitted but nothing imports it.- If your library has its own
babel.config.js, configure the plugins there instead (see Babel below) —ember()picks the config file up automatically.
This supports co-located .css files, inline <style scoped> blocks, and the scopedClass pseudo-helper, same as the other build tools.
In your babel.config.*, add the plugins:
import { scopedCSS } from 'ember-scoped-css/babel';
export default {
plugins: [
// ...
scopedCSS(),
[
'babel-plugin-ember-template-compilation',
{
// ...
transforms: [scopedCSS.template({})],
},
],
// ...
],
// ...
};There are two plugins, but you made only need one:
scopedCSS()- handles removing the import for scopedCSS (which you'd use in GJS and GTS for intellisense, and TypeScript)scopedCSS.template()- transforms your template
layerName: string- Wrap your CSS in a@layerwith this given nameadditionalRoots: string[]- Process additional directories, for example pods or directories from other packages in a monorepo.
If you use TypeScript, or rely on information from TypeScript, you'll want to add the special attributes to the <style> element's attributes list.
These attributes don't exist in normal HTML, which is why they'd error without this change:
Requires
- @glint/ember-tsc 1.0.5 or higher
- @glint/template 1.7.0 or higher
- @glint/tsserver-plugin 2.0.5 or higher
Add ember-scoped-css/types to the types array in your tsconfig.json:
If your project doesn't use compilerOptions.types (note that specifying it disables automatic inclusion of @types/* packages), you can instead import the declarations from a type-declaration file that is included in your project — types/index.d.ts (or similar for apps) or unpublished-development-types/index.d.ts (for libraries):
import 'ember-scoped-css/types';What ember-scoped-css/types provides
It declaration-merges the known attributes for the <style> tag:
import '@glint/template';
declare global {
interface HTMLStyleElementAttributes {
scoped: '';
inline: '';
}
}If you use ember-template-lint for linting the <template>...</template> regions of your components, you'll need to allow the <style> attribute to be used. The easiest way is to disable the no-forbidden-elements rule:
// the template-lintrc
{ // ...
overrides: [
{
files: ['**/*'],
rules: {
'no-forbidden-elements': false,
// or
'no-forbidden-elements': ['meta', 'html', 'script']
},
},
],
}With ember-scoped-css you define styles in an inline <style scoped> block or .css files that are colocated with your components
// ...
<template>
<div data-test-my-component class='hello-class header'>
<b>Hello</b>, world!
</div>
<style scoped>
.hello-class {
color: red;
}
/* the :global() pseudo-class is used to define a global class.
It mean that header class wont be scoped to that component */
.hello-class:global(.header) {
font-size: 20px;
}
b {
color: blue;
}
</style>
</template>Note that <style> (without scoped) will continue to work as it does today and be "global styles"
When using Vite, you can write preprocessor languages inside inline <style> blocks by using the lang attribute. The plugin uses Vite's preprocessCSS API to compile your preprocessor code to plain CSS during the build, then extracts and scopes classes from the compiled CSS.
Examples:
<template>
<p class="scss-hi">hello from scss</p>
<style scoped lang="scss">
$color: rgb(200, 0, 100);
.scss-hi {
color: $color;
&:focus {
outline: none;
}
}
</style>
</template>Notes:
langpreprocessing is only supported when building with Vite. The plugin relies on Vite'spreprocessCSSfunction. If you attempt to uselangwithout Vite, the build will throw a clear error.- Inline styles with
lang(for example<style scoped inline lang="scss">) are downgraded to a non-inline virtual module because preprocessing is asynchronous and cannot run at synchronous Babel-time; you will see a console warning informing you that the style was converted to a virtual CSS import.
inline / conditional CSS
Like the example above, we can specify the scoped attribute on the <style> tag, but if we add the inline attribute as well, the <style> tag will not be extracted to a CSS file during your app's build -- it will be left inline.
This can be useful for conditionally applied styles.
[!IMPORTANT] While using
inlineenables conditional styles, if multiple of the same component are rendered on a page, the CSS from both<style scoped inline>elements will be applied to both renderings of that component.
// ...
<template>
<div data-test-my-component class='hello-class header'>
<b>Hello</b>, world!
</div>
<style scoped inline>
.hello-class {
color: red;
}
/* the :global() pseudo-class is used to define a global class.
It mean that header class wont be scoped to that component */
.hello-class:global(.header) {
font-size: 20px;
}
b {
color: blue;
}
</style>
</template>separate CSS file
/* src/components/my-component.css */
.hello-class {
color: red;
}
/* the :global() pseudo-class is used to define a global class. It mean that header class wont be scoped to that component */
:global(.header) {
font-size: 20px;
}
b {
color: blue;
}NOTE: that if you're using pods, css co-located with templates/routes/etc will need to be named styles.css
Difference with @scope
The @scope at-rule will scope all CSS defined within a <style> tag to the parent element.
<div>
<style>
@scope {
p { color: red; }
}
</style>
<p>this is red</p>
</div>
<p>not red</p>In this example, it is effectively the same as:
<!-- style scoped must be at the root of the template-area -->
<style scoped>
p.inner { color: red; }
</style>
<div>
<p class="inner">this is red</p>
</div>
<p>not red</p>But the nice thing is that you don't need to use classes with @scope.
A potential downside to @scope is that it operates deeply -- where as <style scoped> will only apply its styles to the immediate component -- meaning that nested elements / components don't accidentally get surprise styles.
For example:
const Inner = <template>
<p>
inner (also red)
</p>
</template>;
const Outer = <template>
<div>
<style>
@scope {
p { color: red; }
}
</style>
<p>this is red</p>
<Inner />
</div>
</template>Where as with <style scoped>
const Inner = <template>
<p>
inner (not red)
</p>
</template>;
const Outer = <template>
<style scoped>
p { color: red; }
</style>
<div>
<p>this is red</p>
<Inner />
</div>
</template>There is a scopedClass helper that you can use to pass a class name as an argument to a component. The helper takes a class name and returns a scoped class name. scopedClass helper is replaced at build time so there is no performance hit when running the app.
import { scopedClass } from 'ember-scoped-css';
<template>
<OtherComponent @internalClass={{scopedClass 'hello-class'}} />
<OtherComponent @internalClass={{(scopedClass 'hello-class')}} />
<OtherComponent
@internalClass={{concat (scopedClass 'hello-class') ' other-class'}}
/>
</template>As classes are renamed during the build process you can't directly verify if classes are present in your tests. To solve this problem you can use the scopedClass function from the ember-scoped-css/test-support module. The function takes the class names and path to the CSS file where are the classes defined and returns the scoped class names.
The path to the CSS file is always relative to the V2 addon root no matter where the test is located.
import { scopedClass } from 'ember-scoped-css/test-support';
test('MyComponent has hello-class', async function (assert) {
assert.expect(1);
await render(<template>
<MyComponent />
</template>);
const rewrittenClass = scopedClass(
'hello-class',
'<module-name>/components/my-component'
);
assert.dom('[data-test-my-component]').hasClass(rewrittenClass);
});ember-scoped-css exports a ember-template-lint plugin with one rule scoped-class-helper. This lint rule is intended to help you prevent improper use of the scopedClass helper which might not be immediately obvious during regular development. You can read more information in the lint rules documentation
- Add
ember-scoped-cssplugin to.template-lintrc.js
'use strict';
module.exports = {
plugins: [
+ 'ember-scoped-css/src/template-lint/plugin'
],- Add
scoped-class-helperrule to.template-lintrc.js
'use strict';
module.exports = {
plugins: [
'ember-scoped-css/src/template-lint/plugin'
],
rules: {
+ 'scoped-class-helper': 'error',
+ 'no-forbidden-elements': ['meta', 'html', 'script'], // style removed
}This project is licensed under the MIT License.
{ "compilerOptions": { "types": ["ember-scoped-css/types"] } }