CSS
Source file extensions: .css
Import from Javascript/Typescript
Import globally
import './style.css';
import 'https://web.site/style.css';
This import will transform the CSS file into an ES Module, the CSS is then put inside a <style>
tag in the <head>
of the page, applying the styles globally to the page.
Note that these global CSS imports will not be put inside the component bundle as it is considered a "side effect" of this JavaScript file. All globally imported CSS files are put into a style.css
file in the root of the package. See also how to consume your design system.
Import as a CSSStyleSheet
import style from './style.css';
import style2 from 'https://web.site/style2.css';
This method will create a CSSStyleSheet for use with adoptedStylesheets
, which can also be used in the document (document.adoptedStyleSheets
) or in ShadowDOM (node.shadowRoot.adoptedStyleSheets
).
See Constructible StyleSheets for more information.
It is also possible to import the CSS as a raw string if you need to handle it in a different manner:
import style from './style.css?raw'; // CSS as string
Import as a CSS Module
If the imported file ends with .module.css
, then it's imported as a CSS Module.
/* index.js */
import styles from `./style.module.css`;
...
element.innerHTML = '<div class="' + styles.className + '">';
/* style.module.css */
.className {
color: green;
}
References
- CSS: Cascading Style Sheets
- Constructible Style Sheets
- Adopt a Design System inside your Web Components with Constructable Stylesheets
- CSS Modules
Quick example
style.css
strong {
color: red;
}
div.menu-bar li:hover > ul {
display: block;
}