Use Future CSS In Svelte Today

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:

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.

This works for any Svelte project that uses svelte-preprocess which has built-in support for PostCSS but I’m going to use a skeleton SvelteKit project.

The best part about this approach is when these features are supported in every browser you can just remove PostCSS or keep it for future CSS and you don’t have to use SASS just for nested styles.

To get started install the postcss-preset-env and postcss-load-config plugin to load the PostCSS config.

terminal
npm i -D postcss-preset-env postcss-load-config @types/postcss-preset-env
copy

Create a postcss.config.cjs file at the root of your project.

postcss.config.cjs
const postcssPresetEnv = require('postcss-preset-env')

const config = {
  plugins: [
    postcssPresetEnv({
      stage: 3,
      features: {
        'nesting-rules': true,
        'custom-media-queries': true,
        'media-query-ranges': true
      }
    })
  ]
}

module.exports = config

Here we specified the CSS features using the stage option and enabled the nesting rule and you can learn more from the documentation.

The last step is to enable loading the config in svelte.config.js.

svelte.config.js
import adapter from '@sveltejs/adapter-auto'
import preprocess from 'svelte-preprocess'

/** @type {import('@sveltejs/kit').Config} */
const config = {
	preprocess: preprocess({ postcss: true }),
	kit: {
		adapter: adapter()
	}
}

export default config

To process the CSS include the lang="postcss" attribute inside the <style> tag.

+page.svelte
<style lang="postcss">
  /* ... */
</style>

That’s it! 🎉

Hope you take advantage of future CSS today and you can find the example on GitHub or play with it on StackBlitz.

Thank you for reading! 🏄️

Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub
Subscribe For Updates