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:

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.

terminal
npm i -D postcss-preset-env

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

postcss.config.js
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.

+page.svelte
<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! 🎉

Support

If you want to support the content you're reading or watching on YouTube consider becoming a patreon starting low as 1$ per month.

Become a patreon
Subscribe For Updates
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