Write optimized CSS in Symfony with Stylify

Machy 8
CodeX
Published in
3 min readJun 14, 2022

Introduction

Stylify generates CSS dynamically based on what you write. The syntax is similar to css property:value. Defined utilities are combined with components selectors and in production minified to bare minimum like .color\:red,.button {color:red} to _zx, _ga{color:red}.

With Stylify, you can stay in the Twig templates or PHP files, write selectors and get smallest CSS chunks possible for each page separately 🤟

Symfony Quick Setup

The easiest way to start is to use the Symfony Skeleton and Webapp packages.

Add the HpController src/Controller/HpController.php

and the homepage template templates/hp.html.twig.

Stylify Integration

Install Stylify universal plugin.

Update the webpack.config.js. Import Stylify, add plugin and the hp style entry.

Change app.css in assets/app.js to 'layout.css' and add the css link into the hp.html.twig.

Styling the website

When the setup is finished edit the hp.html.twig

and run npm run dev.

Stylify will find the color:blue selector, and generate the css for it. .color\:blue{color:blue} into the homepage.css.

Some code often needs to be reused accross multiple pages. It’s not a good idea to have bloated templates by utilities and hardcoded units in the selectors. Let’s define a container component and some variables.

Open the webpack.config.js and edit the Stylify plugin config:

Now we can update the base.html.twig

and the hp.html.twig

Sometime, some components are used only one place. It doesn’t make sense to define them in the webpack.config.js. We can also define components, variables and etc directly in the file where they are used. Stylify has a content options for that.

Let’s add a paragraph component in the hp.html.twig:

The production build

When we run the build for production npm run build, Stylify automatically mangles all recognized selectors and generates optimized CSS.

Optimized hp.html.twig:

Optimized hp css:

The example can be also found on Stylifycss.com website.

Configure anything you need

The examples above doesn’t include everything Stylify can do:

Feel free to checkout the docs to learn more 💎.

Let me know what you think!

I will be happy for any feedback! The Stylify is still a new Library and there is a lot of space for improvement 🙂.

--

--

Machy 8
CodeX
Writer for

Webdeveloper ✨ | Author of https://stylifycss.com 🎨 | Frontend-dev at https://slevomat.cz 🏝️ | Previously https://lekarna.cz 🌿