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

You can subscribe on YouTube, or consider becoming a patron if you want to support my work.

Patreon
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