Use Future CSS In Svelte Today
Published Sep 2, 2022
Table of Contents
Use Future CSS Today
With so many great CSS features like container queries coming to browsers the excitement around CSS has never been greater.
Here are some of the CSS features Iโm excited about:
- Nesting rules
- Cascade layers
- Custom media queries
- Media query ranges
:has()
and:is()
pseudo class- Trigonometric functions
Some of these features might be already supported by some browsers but what if you wanted to use those features today?
In that case you can use PostCSS that describes itself as โA tool for transforming CSS with JavaScriptโ.
Set Up PostCSS
PostCSS is to CSS what Babel is to JavaScript and it lets you use future CSS today by converting modern CSS to something most browsers can understand using polyfills.
๐ฟ๏ธ A polyfill is a piece of code used to provide functionality on older browsers that donโt natively support it.
To start using modern CSS today itโs simple as adding the postcss-preset-env plugin for PostCSS in your Svelte project and enabling the options you want.
To get started install the postcss-preset-env
plugin.
npm i -D postcss-preset-env
Create a postcss.config.js
file at the root of your project.
import postcssPresetEnv from 'postcss-preset-env'
/** @type {import('postcss-preset-env').Config} */
const config = {
plugins: [
postcssPresetEnv({
features: { 'nested-rules': true },
}),
],
}
export default config
Stage 2 features are enabled by default but you can enable other features and look at more options from postcss-preset-env.
Donโt forget to include the lang="postcss"
attribute inside the <style>
tag.
<style lang="postcss">
@custom-media --md (min-width: 768px);
.grid {
display: grid;
grid-template-columns: 1fr;
@media (--md) {
grid-template-columns: repeat(4, 1fr);
}
}
</style>
Thatโs it! ๐