Tag: Tailwind

Color Theming with CSS Custom Properties and Tailwind

Custom properties not only enable us to make our code more efficient, but allow us to work some real magic with CSS too. One area where they have huge potential is theming. At Atomic Smash we use Tailwind CSS, a utility class framework, for writing our styles. In this article, we’ll look at how custom properties can be used for theming, and how we can integrate them with Tailwind to maximize the reusability of our code. We won’t cover getting up and running with Tailwind — check out the official documentation for that — but even if you’re new to it you might find some of these tips useful.

Theming overview

Let’s say we have a “Call To Action” (CTA) component with a heading, body copy, and button.

A box with a light red heading that reads join our mailing list above a dark red body that reads be the first to hear about our new offerings right before a red signup button.

Writing regular (non-Tailwind) CSS for this color scheme would look something like this:

.cta {   background-color: #742a2a; // dark red   color: #ffffff; //white }      .cta__heading {   background-color: #e53e3e; // medium red   color: #742a2a; } 
 .cta__button {   background-color: #e53e3e; }

Using Tailwind, we would apply these colors as utility classes in our HTML:

<div class="bg-red-900 text-white">   <h3 class="bg-red-600 text-red-900">Join our mailing list</h3>   <div>     <p>Be the first to hear about our new offerings</p>     <button class="bg-red-600" type="button">Sign up</button>   </div> </div>

I’ve deliberately left out classes relating to anything other than the basic color scheme, but you can see the example in its entirety in this demo:

Now, if we wanted to apply a different color scheme to our component, we would need to override the color values of our original component. Without Tailwind, a common way to do that would be to append a theme class to the component itself, and redefine the color values lower down in the cascade. So for a component with a modifier class of .cta--blue (using the BEM convention) we’ll apply the CSS values for a blue color scheme:

.cta--blue {   background-color: #2a4365; // dark blue } 
 .cta--blue .cta__heading {   background-color: #3182ce; // medium blue   color: #2a4365; } 
 .cta--blue .cta__button {   background-color: #3182ce; }
A box with a light blue heading that reads join our mailing list above a dark bluebody that reads be the first to hear about our new offerings right before a blue signup button.

If we’re using Sass or another preprocessor, it’s likely we’ll make life easier for ourselves by using variables for those color names, and we might nest the .cta__heading and .cta__body selectors. It doesn’t exactly make our code more concise, but it does make it more manageable by having a single place to update those values.

Now, suppose we have 10 different color schemes, as was my experience on a recent project. Our code starts to get longer, as we’re basically duplicating the above example 10 times in order to change those color values. Now imagine every component in our design system needs 10 color schemes, and many of those components are far more complex than our simple CTA. Maybe our themes need different fonts too. Suddenly we have a lot of CSS to write.

Theming with Tailwind

If we’re using Tailwind, on the other hand, we’d need to change multiple classes in the HTML itself. Even if we’re using a JavaScript framework, like React or Vue, this is not exactly a trivial task. In order to ensure unused styles are removed in a production build, Tailwind discourages the use of string concatenation for class names (at the time of writing). So building our themes means potentially piling a lot of logic into our components.

Theming with Custom Properties

By using custom properties for our color themes, we can drastically reduce the amount of code we need to write, and alleviate the maintenance burden. Let’s first take a look at how we can do this in regular CSS.

We define our custom properties as variables on the :root selector, making them global variables. (The body selector would serve us just as well.) Then we can use those variables in a selector, in place of our color property values:

:root {   --primary: #742a2a; // dark red;   --secondary: #e53e3e; // medium red } 
 .cta {   background-color: var(--primary);   color: white; } 
 .cta__heading {   background-color: var(--secondary);   color: var(--primary); } 
 .cta__button {   background-color: var(--secondary); }

This is where the real magic happens: now the code for creating each of our themes becomes a case of only updating those custom property values. The new values will be inherited wherever we apply our theme class:

.th-blue {   --primary: #2a4365; // dark blue   --secondary: #3182ce; // medium blue }

If we want a blue color scheme, we can apply that .th-blue class to the component, or even use it on the <body> tag to apply to apply a page-wide theme, which can be overridden on individual components as desired. Using a utility class potentially saves us writing even more code compared to a component-specific class (such as .cta--blue in the original code), as it could be applied anywhere in our codebase.

Handling older browsers

Like many agencies, plenty of our clients at Atomic Smash still require us to support Internet Explorer 11. While I’m okay with a progressive enhancement approach in most cases (by providing simpler fallback layouts for browsers that don’t support CSS Grid, for instance), I find theming is one area that often doesn’t allow for easy compromise. Clients want their brand colors and fonts seen, even on older browsers. Providing fallbacks using feature queries would entail a lot of extra work that would negate the benefits of using custom properties in the first place. To overcome this, we need a polyfill.

There are a couple of options for polyfilling custom properties in IE 11.

postcss-custom-properties

The first is using a PostCSS plugin called postcss-custom-properties. If you’re already using PostCSS in your workflow, this is fairly simple to add. It works by processing your CSS and outputting the result of the variable as the property value. So if you have the following CSS:

:root {   --color: red; } 
 h1 {   color: var(--color); }

The processed result will be:

h1 {   color: red;   color: var(--color); }

Browsers that don’t support custom properties will ignore the second rule and fall back to the regular property value. There is also an option to remove the rules with the custom properties in the output, so the file size will be smaller. This means that no browsers will get the custom property — which is an issue if you’re updating variables dynamically — but you’ll be able to use them for static values in your code with no ill effects.

Unfortunately this polyfill has some limitations:

  1. You need to specify the file (or files) in your config where you’re defining the custom properties.
  2. Custom properties can only be defined on the :root selector.

The first limitation is relatively trivial, but the second unfortunately renders this polyfill entirely useless for our theming use case. It means we can’t redefine variables on a selector to create our themes.

ie11CustomProperties

This polyfill option involves serving a client-side script, rather than preprocessing the CSS. We can add the following script to our head to ensure the polyfill will only be loaded in IE 11:

<script>window.MSInputMethodContext && document.documentMode && document.write('<script src="https://cdn.jsdelivr.net/gh/nuxodin/ie11CustomProperties@4.1.0/ie11CustomProperties.min.js"></script>');</script>

This permits us to enjoy the full benefits of custom properties as in the examples here, so it’s the solution I decided to go with. It has a limitation where custom properties set in style attributes aren’t polyfilled. But I’ve tested it for the theming example above and it works just fine.

But what does this have to do with Tailwind? 

As we’ve already seen, utility classes — single-purpose classes that can be applied anywhere in our HTML — can make our code more reusable. That’s the main selling point of Tailwind and other utility class frameworks — the size of the CSS file you ship should end up smaller as a result. Tailwind makes multiple color classes available: .bg-red-medium would give us a red background-color property value, .text-red-medium for color and so on for border, box-shadow, or any place you can think of that you might need a color value. 

Colors can be defined in a config file:

module.exports = {   theme: {     colors: {       red: {         medium: '#e53e3e',         dark: '#742a2a'       },       blue: {         medium: '#3182ce',         dark: '#2a4365'       }     }   } }

If we want to use custom property values for our Tailwind classes, we can specify them in the config:

module.exports = {   theme: {     colors: {       'th-primary': 'var(--primary)',       'th-secondary': 'var(--secondary)'     }   } }

I’m prefixing my colors and theme-related class names with th- so that it’s obvious they’re specifically related to theming, but feel free to use whatever convention suits you.

Now those classes will be available to us through Tailwind. Using .bg-th-primary gives us the equivalent of writing:

.some-element {   background-color: var(--primary); }

In our CSS we can define our custom properties for our themes as before:

:root {   --primary: #742a2a;   --secondary: #742a2a; } 
 .th-blue {   --primary: #2a4365;   --secondary: #3182ce; }

Let’s apply those classes to our HTML. The first example gives us a component with our default theme (the variables defined on the :root). The second has our blue theme. The only difference is the addition of the .th-blue class on the component. (Once again, I’ve omitted the classes unrelated to the theme, for brevity and clarity.)

<!--Component with default (red) theme--> <div class="bg-th-primary">   <h3 class="bg-th-secondary text-th-primary">Join our mailing list</h3>   <div>     <p>Be the first to hear about our new offerings</p>     <button class="bg-th-secondary" type="button">Sign up</button>   </div> </div> 
 <!--Component with blue theme--> <div class="th-blue bg-th-primary">   <h3 class="bg-th-secondary text-th-primary">Join our mailing list</h3>   <div>     <p>Be the first to hear about our new offerings</p>     <button class="bg-th-secondary" type="button">Sign up</button>   </div> </div>

Using the config as a style guide

Tailwind encourages you to define all variables in the config, and personally I agree that it’s a better approach. It means that the config file can be a single source of truth rather than (potentially) ending up with multiple places to define your colors and other theme values. Luckily, we can also use values from the Tailwind config file for our custom properties. We’ll need to first define all of our colors in the config (assuming we’re not using the default color palette included with Tailwind):

module.exports = {   theme: {     colors: {       red: {         medium: '#e53e3e',         dark: '#742a2a'       },       blue: {         medium: '#3182ce',         dark: '#2a4365'       },       'th-primary': 'var(--primary)',       'th-secondary': 'var(--secondary)'     }   } }

Then we can access the theme object in the CSS:

:root {   --th-primary: theme('colors.red.dark');   --th-secondary: theme('colors.red.medium'); } 
 .th-blue {   --th-primary: theme('colors.blue.dark');   --th-secondary: theme('colors.blue.medium'); }

Wrapping up

I’m really excited about the benefits of being able to use custom properties without having to worry about browser support, even more so to be able to integrate them smoothly with our existing workflow. It’s hard to overstate the amount of time they will save us for theming. I hope that even if you’re not a Tailwind user, this article might encourage you to give custom properties a go for this use case.


The post Color Theming with CSS Custom Properties and Tailwind appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,

An Eleventy Starter with Tailwind CSS and Alpine.js

When I decided to try to base my current personal website on Eleventy, I didn’t want to reinvent the wheel: I tested all the Eleventy starters built with Tailwind CSS that I could find in Starter Projects from the documentation.

Many of the starters seemed to integrate Tailwind CSS in a contrived way. Also, some of them seemed to assume that no one updates Tailwind’s configuration on the fly while working on a website. That’s why I integrated Eleventy with Tailwind CSS and Alpine.js myself. I have reason to believe that you’ll like the simplicity of my solution.

Good design is as little design as possible.

—Dieter Rams, 10 Principles for Good Design

If you’re uninterested in the details, feel free to grab my starter and jump right in.

Getting started

I’m going to assume you have a general understanding of Tailwind CSS, HTML, JavaScript, Nunjucks, the command line, and npm.

Let’s start by with a new a folder, then cd to it in the command line, and initialize it with a package.json file:

npm init -y

Now we can install Eleventy and Tailwind CSS. We’ll throw in PostCSS as well:

npm install --save-dev @11ty/eleventy tailwindcss postcss-cli

We need to create a page to test whether we’ve successfully set things up. In a real use case, our pages will use templates, so we’ll do that here as well. That’s where Nunjucks fits into the mix, serving as a templating engine.

Let’s make a new file called index.njk in the project folder. We’ll designate it as the homepage:

{% extends "_includes/default.njk" %} 
 {% block title %}It does work{% endblock %} 
 {% block content %}   <div class="fixed inset-0 flex justify-center items-center">     <div>       <span class="text-change">Good design</span><br/>       <span class="change">is<br/>as little design<br/>as possible</span>     </div>   </div> {% endblock %}

Basic templating

Now let’s create a new folder in the project folder called _includes (and yes, the folder name matters). Inside this new folder, we’ll create a file called default.njk that we’ll use as the default template for our layout. We’ll keep things simple with a basic HTML boilerplate:

<!DOCTYPE html> <html lang="en">   <head>     <title>       {% block title %}Does it work?{% endblock %}     </title>     <meta charset="UTF-8"/>     {% if description %}       <meta name="description" content="{{description}}"/>     {% endif %}     <meta http-equiv="x-ua-compatible" content="ie=edge"/>     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover"/>     <link rel="stylesheet" href="/style.css?v={% version %}"/>     {% block head %}{% endblock %}   </head>   <body>     {% block content %}       {{ content | safe }}     {% endblock %}   </body> </html>

Configuring Tailwind CSS

Let’s take care of a test for Tailwind CSS in as few moves as possible. First, create a new subfolder called styles and a file in it called tailwind.config.js:

module.exports = {   theme: {     colors: {       change: "transparent"     }   },   variants: {},   plugins: [], }

Then, create a file called tailwind.css in that same styles folder:

/* purgecss start ignore */ @tailwind base; /* purgecss end ignore */ 
 .change {   color: transparent; } 
 /* purgecss start ignore */ @tailwind components; /* purgecss end ignore */ 
 @tailwind utilities;

We’re done with the styles folder for now. What we do need is a configuration file that tells PostCSS to use Tailwind CSS, which we can get by creating a new file in the root directory of the project folder called postcss.config.js. Here’s how we require Tailwind CSS and its configuration file with PostCSS:

module.exports = {   plugins: [     require(`tailwindcss`)(`./styles/tailwind.config.js`)   ], };

Starting and building the project

Now let’s create another new file in the same root directory called .gitignore. This will allow us to define what files to skip when committing the project to a repo, like on GitHub:

_site/ _tmp/ .DS_Store node_modules/ package-lock.json

Next, is another new file, this time one that tells Eleventy what it can ignore, called .eleventyignore. It only needs one line:

node_modules

OK, now we will create a file called .eleventy.js (note the leading dot!) that basically configures Eleventy, telling it what files to watch and where to save its work:

module.exports = function (eleventyConfig) {   eleventyConfig.setUseGitIgnore(false); 
   eleventyConfig.addWatchTarget("./_tmp/style.css"); 
   eleventyConfig.addPassthroughCopy({ "./_tmp/style.css": "./style.css" }); 
   eleventyConfig.addShortcode("version", function () {     return String(Date.now());   }); };

We can now update the package.json file with all of the scripts we need to start and build the site during development. The dependencies should already be there from the initial setup.

{   "scripts": {     "start": "eleventy --serve & postcss styles/tailwind.css --o _tmp/style.css --watch",     "build": "ELEVENTY_PRODUCTION=true eleventy & ELEVENTY_PRODUCTION=true postcss styles/tailwind.css --o _site/style.css"   },   "devDependencies": {     "@11ty/eleventy": "^0.11.0",     "postcss-cli": "^7.1.0",     "tailwindcss": "^1.4.6"   } }

Hey, great job! We made it. Build the project to generate the initial CSS — this step is only required the very first time we set up. From the command line:

npm run build

And — drumroll, please — let’s officially start the site:

npm run start

Open the page http://localhost:8080 in your browser. It’s not gonna look like much, but check out the page title in the browser tab:

It does work!

We can still do a little more checking to make sure everything’s good. Open up /styles/tailwind.config.js and change the transparent color value to something else, say black. Tailwind’s configuration should reload, along with the page in your browser.

Don’t lose sight of your browser and edit /styles/tailwind.css by changing transparent to black again. Your CSS file should reload and refresh in your browser.

Now we can work nicely with Eleventy and Tailwind CSS!

Optimizing the output

At this point, Tailwind CSS works with Eleventy, but the CSS file is huge. The generated HTML isn’t perfect either because it contains stuff like redundant newline characters. Let’s clean it up:

npm install --save-dev @fullhuman/postcss-purgecss postcss-clean html-minifier

Open up postcss.config.js and replace what’s in there with this:

module.exports = {   plugins: [     require(`tailwindcss`)(`./styles/tailwind.config.js`),     require(`autoprefixer`),     ...(process.env.ELEVENTY_PRODUCTION       ? [           require(`postcss-clean`),           require(`@fullhuman/postcss-purgecss`)({             content: ["_site/**/*.html"],             defaultExtractor: (content) =>               content.match(/[w-/:]+(?<!:)/g) || [],             whitelist: [],             whitelistPatterns: [/body/, /headroom/, /ril/],           }),         ]       : []),   ], };

In the future, in the process of creating your website, if something looks wrong after you build the project and you have the impression that fragments of CSS are missing, add “ignored” class names to the whitelist in the file above.

Add the following line to the beginning of the .eleventy.js file:

const htmlmin = require("html-minifier");

We also need to configure htmlmin in .eleventy.js as well:

eleventyConfig.addTransform("htmlmin", function (content, outputPath) {     if (       process.env.ELEVENTY_PRODUCTION &&       outputPath &&       outputPath.endsWith(".html")     ) {       let minified = htmlmin.minify(content, {         useShortDoctype: true,         removeComments: true,         collapseWhitespace: true,       });       return minified;     } 
     return content; });

We’re using a transform here which is an Eleventy thing. Transforms can modify a template’s output. At this point, .eleventy.js should look like this:

const htmlmin = require("html-minifier"); 
 module.exports = function (eleventyConfig) {   eleventyConfig.setUseGitIgnore(false); 
   eleventyConfig.addWatchTarget("./_tmp/style.css"); 
   eleventyConfig.addPassthroughCopy({ "./_tmp/style.css": "./style.css" }); 
   eleventyConfig.addShortcode("version", function () {     return String(Date.now());   }); 
   eleventyConfig.addTransform("htmlmin", function (content, outputPath) {     if (       process.env.ELEVENTY_PRODUCTION &&       outputPath &&       outputPath.endsWith(".html")     ) {       let minified = htmlmin.minify(content, {         useShortDoctype: true,         removeComments: true,         collapseWhitespace: true,       });       return minified;     } 
     return content;   }); };

Alright, let’s run npm run start once again. You’ll see that nothing has changed and that’s because optimization only happens during build. So, instead, let’s try npm run build and then look at the _site folder. There shouldn’t be a single unnecessary character in the index.html file. The same goes for the style.css file.

A project built like this is now ready to deploy. Good job! 🏆

Integrating Alpine.js

I decided to switch to Eleventy from Gatsby.js because it just felt like too much JavaScript to me. I’m more into the reasonable dose of vanilla JavaScript mixed with Alpine.js. We won’t get into the specifics of Alpine.js here, but it’s worth checking out Hugo DiFrancesco’s primer because it’s a perfect starting point.

Here’s how we can install it to our project from the command line:

npm install --save-dev alpinejs

Now we need to update .eleventy.js with this to the function that passes things through Alpine.js:

eleventyConfig.addPassthroughCopy({   "./node_modules/alpinejs/dist/alpine.js": "./js/alpine.js", }); 

Lastly, we’ll open up _includes/default.njk and add Alpine.js right before the closing </head> tag:

<script src="/js/alpine.js?v={% version %}"></script>

We can check if Alpine is working by adding this to index.njk:

{% extends "_includes/default.njk" %} 
 {% block title %}It does work{% endblock %} 
 {% block content %}   <div class="fixed inset-0 flex justify-center items-center">     <div>       <span class="text-change">Good design</span><br/>       <span class="change">is<br/>as little design<br/>as possible</span><br/>       <span x-data="{message:'🤖 Hello World 🤓'}" x-text="message"></span>     </div>   </div> {% endblock %}

Launch the project:

npm run start

If Alpine.js works, you’ll see “Hello World” in your browser. Congratulations, times two! 🏆🏆


I hope you can see how quick it can be to set up an Eleventy project, including integrations with Nunjucks for templating, Tailwind for styles and Alpine.js for scripts. I know working with new tech can be overwhelming and even confusing, so feel free to email me at csstricks@gregwolanski.com if you have problems starting up or have an idea for how to simplify this even further.

The post An Eleventy Starter with Tailwind CSS and Alpine.js appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

A Better Approach for Using Purgecss with Tailwind

Greg Kohn looks at how to use Purgecss — a tool that helps remove unused styles — and Tailwind — a utility-based CSS framework — and why we might want to pair these tools together:

Tailwind, by intention, is aiming to equip you with an arsenal of utility classes by generating more than you need. There are some best practices which will help keep this overall build size down, like limiting your colors and breakpoints or turning off the modules by default before adding them as necessary. Still, you’ll inevitably generate classes that go unused. And honestly, approaching your configuration with an unrelenting miserly attitude will slow you down and make development less fun. By leaning on Purgecss, there’s no worry that the CSS your users download will only include classes that are ultimately needed.

I’ve never used Tailwind or Purgecss, but I reckon the latter could be particularly useful if you have a giant old codebase and you don’t have the resources to refactor things just yet. I guess my only concern with introducing a tool like that is it could encourage folks to not refactor large and problematic areas in their styles – taking the safest route with this tool instead.

For more info about Tailwind, though, Ben Tinsley wrote a great post a while back about how to get started and Nick Basile showed us how to style a form with Tailwind.

Direct Link to ArticlePermalink

The post A Better Approach for Using Purgecss with Tailwind appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]