DEV Community

Ciaran
Ciaran

Posted on • Originally published at ciaran.co.za

How to Create a Tailwind CSS + WordPress Theme Boilerplate

A few months ago, when I was first getting started with Adam Wathan’s TailwindCSS, I was really put off by how hard I was finding it to install as a part of various frameworks. As such, I decided to put this guide together to demonstrate how to scaffold an efficient TailwindCSS + WordPress development setup.

In this guide we’ll go through the pros and cons of using TailwindCSS with WordPress, how to quickly set up a template that I created (so you don’t have to install anything yourself), and how to create a blank theme from scratch which uses Tailwind.

If you have any questions or recommendations, don’t hesitate to tweet me @parabyl! I’m always keen to get second opinions on what I’m doing, and feedback on the projects I’m working on.

Jump to: Quick Setup

Why Use TailwindCSS with WordPress

Depending on what you regard as best practices, you might think using a utility-based CSS framework with WordPress a bit confusing – aren’t we meant to be keeping our HTML clean and readable?

Well, it turns out that Tailwind offers some gains where my previous setup of WordPress + Elementor + A Solid Theme was giving me issues. Let’s explore a few of these areas in more detail.

The 4 Benefits of TailwindCSS for Theme Development

There are four standout benefits that I see using TailwindCSS, specifically for theme development, compared to other frameworks. These are all pros that any self-respecting designer should at least understand, if not agree with.

Theming Capabilities

Theming is important to you, if you’re reading this. It’s a practice that allows us to define common styles across an entire project, allowing for brand identity and visual hierarchy to shine through as it should. Tailwind’s tailwind.config.js file allows us to set up parameters such as fonts, colours, and utilities, as well as allowing us to overwrite the default Tailwind styles.

This way, if we wanted to expand our project into a new realm (say, launching a product under the same company name), we could simply copy over the tailwind.config.js file to the new project, using the exact same base CSS setup.

Performance Optimization

TailwindCSS (as of version 1.8) is just under 200kb Gzipped. This is small, however if we take the stylesheet for this website, it’s just under 15kb (TINY!).

This is thanks to Tailwind using PurgeCSS – a module which mixes CSS classes you actually used into your output files. Didn’t use max-w-lg? It won’t exist in your output style.css.

Readability

One of my favourite parts of TailwindCSS is how readable it is, once you get to grips with the lexicon of the framework. To be able to dip into a WordPress theme and see styling, logic, and markup all neatly positioned together is a major pro.

Further, when you combine the addition of Tailwind CSS classes with conditional logic in your .php files, you’re on your way to building some really cool state or logic-responsive components in your theme.

The TailwindCSS Community

Being a large and popular growing framework, there are so many resources out there for Tailwind – from live websites, to examples and tutorials, and even free component libraries for you to use. This is one of the biggest advantages of using a framework which is rapidly growing in popularity, as it means when you run into an issue, someone else has likely found a solution.

Quick Start: HTML5Blank + TailwindCSS Template

So, all that intro aside, let’s begin with the template I created. I’ll teach you to set a theme up from scratch with Tailwind further down in this tutorial, however for now let’s just explore the simple setup option.

You can download the template here.

Theme Installation & Setup

First, clone the repo I published as a starter. It’s based on HTML5Blank as this is one of the best blank themes you can use for learning theme development.

git clone https://github.com/knightspore/wordpress-tailwind.git
Enter fullscreen mode Exit fullscreen mode

Next, you’ll need to install dependencies using your preferred package manager

npm install --save-dev
or
yarn
Enter fullscreen mode Exit fullscreen mode

Now you’re ready to start using the theme! Run npm run dev or yarn dev to compile your assets unminified, watch to re-compile theme every time you save, or prod to run your production build.

You can edit assets/style.css to edit your CSS (for @apply and non-inline styles), and assets/main.js to edit your Javascript.

Creating a WordPress Theme using TailwindCSS

Now that you’ve got the option of quick setup, let’s run over an installation on a blank WordPress theme in case you don’t want to use HTML5Blank.

Setting Up your Theme

To begin, let’s navigate to wp-content/themes and run mkdir example (where ‘example’ is your theme name). In order for WordPress to recognize this folder as a theme, we need to add a few items.

Let’s open the folder and run touch style.css index.php. You should now see these two files appear, and be able to use the blank theme in Appearance > Themes in your WordPress Admin dashboard. Let’s also run touch header.php footer.php as we’ll need these later.

Installing Laravel Mix

Next, we need to install Laravel mix. This is the cleanest wrapper for webpack that I’ve found, and it works really nicely for wordpress theme development as a lot of the confusing syntax has been removed.

First, run

npm install laravel-mix cross-env --save-dev 
or 
yarn add laravel-mix cross-env
Enter fullscreen mode Exit fullscreen mode

Next, run

cp node_modules/laravel-mix/setup/webpack.mix.js ./
Enter fullscreen mode Exit fullscreen mode

You should now see a node_modules/ directory, as well as package.json and webpack.mix.js files in your root directory.

If we look inside our Laravel Mix Config file, we can see a simple setup has been scaffolded. It’s taking assets from a folder called src/ and compiling them into a folder called dist/. To complete our setup of mix, we need to create the source assets that mix is looking for.

Run

mkdir src; touch src/app.js src/app.css
Enter fullscreen mode Exit fullscreen mode

(Note: we’re using CSS instead of SASS here as Tailwind does not require pre-processors)

Finally, copy and paste the recommended Laravel Mix Build Scripts into package.json

"scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "npm run development -- --watch",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
}
Enter fullscreen mode Exit fullscreen mode

Installing TailwindCSS

To install Tailwind, let’s begin by adding it with our package manager

yarn add tailwindcss
or
npm install tailwindcss --save-dev
Enter fullscreen mode Exit fullscreen mode

Next, add the TailwindCSS directives to your src/app.css file.

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Finally, we need to update webpack.mix.js to build assets correctly. As with most of these code snippets, the TailwindCSS installation page has got us covered once again: replace the file contents with the following.

let mix = require('laravel-mix');

mix.js('src/app.js', 'js/app.js')
    .postCss('src/app.css', 'style.css', [
        require('tailwindcss'),
        require('autoprefixer'),
      ]);
Enter fullscreen mode Exit fullscreen mode

Generate a blank config file using npx tailwindcss init (you’ll want this file later) and we’re ready to go!

Building Your Assets with Laravel Mix

To test our build, run npm run dev or yarn dev. You should see some confirmation from your package manager upon running this command.

Let’s try adding some basic HTML to our index.php to see if Tailwind is working properly.

<h1 class=”text-xl text-red-500”>Hello World</H1>
Enter fullscreen mode Exit fullscreen mode

You can run your watch script at this point if you’re working with your src/app.css file instead of inline styles.

If you’ve followed correctly, the styling on your H1 should not work immediately. We first need to add the wp_head() directive to our header. This will add references such as our stylesheet into the

of our theme.

To do this, let’s first generate a simple HTML setup in our header.php and add our header directive to it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <?php wp_head(); ?>
</head>
<body>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

From here, we can cut the last two lines and paste them into our footer.php file. Next, let’s include our header and footer in our index.php file.

<?php get_header(); ?>
<h1 class="text-xl text-center text-red-500">Hello World</h1>
<?php get_footer(); ?>
Enter fullscreen mode Exit fullscreen mode

And finally, we need to enqueue our stylesheet by creating functions.php and adding the following

<?php
wp_enqueue_style('style', get_stylesheet_uri());
?>
Enter fullscreen mode Exit fullscreen mode

Now, when you refresh your site, you should see your inline styles showing.

Controlling TailwindCSS File Size

Now, you might have noticed that when we compiled our styles, our output CSS was a whopping 2.28mb. This is because, by default, Tailwind includes all its possible utilities in our output file.

Luckily, as I mentioned earlier, Tailwind uses PurgeCSS to easily remove unused classes from our output. We just need to update the purge section of our tailwind.config.js file.

purge: [
    './**/*.php',
]
Enter fullscreen mode Exit fullscreen mode

Now, when we run yarn prod, our output is looking much smaller! This purging will only happen when you’re running a production build, so that your computer isn’t working overtime to purge assets each time you hit save during development.

Closing Notes

Congrats, you’ve now got a working, performance optimized WordPress Theme running TailwindCSS! Please get in touch if you’ve got any notes or suggestions to make this process easier, or if you want to share your sites that you’ve built with Tailwind and WordPress.

Latest comments (1)

Collapse
 
digital_hub profile image
hub

good day dear Ciaran,

many thank you so much for spending your time creating and posting this article.

i just found your article and i like it. The way you talk about CSS and Wordpress-development.

Many thanks for the article it is just great!! It looks very promising and your thoughts regarding the usage of Tailwind CSS for Wordpress
development are interesting. Many thanks for your inspiring ideas.

i am currently working on some issues - that have to do with the CSS and google fonts.

to begin with the beginning:i have found out that my wordpress-site fetches two google fonts:

one of them is montserrat

i decided to host them locally. so i have to

a. fetch the fonts
b. correct the css code

with the following tool i fetch them

google-webfonts-helper.herokuapp.c...

here i have the option to add the paths - to customize the path in the css-data

/* montserrat-regular - latin / u/font-face { font-family: 'Montserrat'; font-style: normal; font-weight: 400; src: url('../fonts/montserrat-v25-latin-regular.eot'); / IE9 Compat Modes / src: local(''), url('../fonts/montserrat-v25-latin-regular.eot?#iefix') format('embedded-opentype'), / IE6-IE8 / url('../fonts/montserrat-v25-latin-regular.woff2') format('woff2'), / Super Modern Browsers / url('../fonts/montserrat-v25-latin-regular.woff') format('woff'), / Modern Browsers / url('../fonts/montserrat-v25-latin-regular.ttf') format('truetype'), / Safari, Android, iOS / url('../fonts/montserrat-v25-latin-regular.svg#Montserrat') format('svg'); / Legacy iOS */ } Customize folder prefix (optional):

and now i have to add a path to set the correct path - (that means to customize the path )

../fonts/

some additional thought: what makes me wonder is the fact that some of the examples show full paths as reference - others dont:

see the following examples;

a. wp-ninjas.de/wordpress-google-font...

url("https://wp-ninias.de/fonts/muilti-latin-300.woff2") format (
url("https://wp-ninias.de/fonts/muilti-latin-300.woff") format (

b. pixelgrade.com/docs/advanced-custo...

Copy the URL Path field and paste it before each URL in the Embed Code field. The example code will look like this:

@font-face {
font-family: 'Name of the font';
src: url('http://yourwebsite.com/wp-content/uploads/fonts/11148/name-of-the-font-file.woff2') format('woff2'),
url('http://yourwebsite.com/wp-content/uploads/fonts/11148/name-of-the-font-file.woff') format('woff');
}

c. themeisle.com/blog/custom-fonts-wo...

Once the file is in place, open up your child theme’s stylesheet. Now you’ll need to call on that font so you can use it, via a snippet that should look like this:

`

@font-face {
font-family: New Font;
src: url(yourwebsite.com/wp-content/themes/...);
font-weight: normal;
}

`

and now compare it with the following example here:

  1. Copy CSS: (default is Best Support) Modern Browsers Choose Best Support if old browsers still need to be supported. Formats in this snippet: [eot,woff,woff2,ttf,svg]

Code:
/* montserrat-regular - latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: url('../fonts/montserrat-v25-latin-regular.eot'); /* IE9 Compat Modes */
src: local(''),
url('../fonts/montserrat-v25-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/montserrat-v25-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
url('../fonts/montserrat-v25-latin-regular.woff') format('woff'), /* Modern Browsers */
url('../fonts/montserrat-v25-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/montserrat-v25-latin-regular.svg#Montserrat') format('svg'); /* Legacy iOS */

see the helper-tool google-webfonts-helper.herokuapp.c...

the question: so the question is: how to set the path correct for the CSS... which path should we use here!?

Dear Ciaran, i look forward to hear from you