Home > Web Front-end > CSS Tutorial > Adding Tailwind CSS to New and Existing WordPress Themes

Adding Tailwind CSS to New and Existing WordPress Themes

William Shakespeare
Release: 2025-03-13 13:00:18
Original
689 people have browsed it

Adding Tailwind CSS to New and Existing WordPress Themes

Since I started making WordPress websites, in about 15 years, nothing has had a greater impact (and a big gap) on how productive I was and how much I enjoyed with front-end development.

When I started using Tailwind, there was a newest, first-party repository on GitHub that described how to use Tailwind in WordPress. The repository has not been updated since 2019. But the lack of updates does not illustrate the practicality of Tailwind for WordPress developers. By having Tailwind work as its best while still WordPress is the best part of both platforms and build modern websites in less time.

The minimum settings example in this article is designed to update the original settings repository and modified to be compatible with the latest versions of Tailwind and WordPress. This approach can be extended to a variety of WordPress themes, from derived default themes to fully custom ones.

Why WordPress developers should follow Tailwind

Before we discuss setting, it's worth reviewing how Tailwind works and what it means in a WordPress environment.

Tailwind allows you to style HTML elements with pre-existing utility classes, eliminating the need to write most or all of your website's CSS yourself. (Think about classes like hidden for display: hidden or uppercase for text-transform: uppercase .) If you have used frameworks like Bootstrap and Foundation in the past, the biggest difference you will find in Tailwind CSS is its blank slate method of design and its lightweight feature of CSS only, which only includes CSS resets. These properties allow highly optimized websites without pushing developers toward the aesthetic built-in of the framework itself.

Furthermore, unlike many other CSS frameworks, "standard" builds for loading Tailwind CSS from existing CDNs cannot be done. The generated CSS file will be too large due to all utility classes included. Tailwind provides a "Play CDN", but it is not used in production environments because it significantly reduces the performance advantages of Tailwind. (However, it is really handy if you want to do rapid prototyping or otherwise experiment with Tailwind without actually installing it or setting up the build process.)

This requires using Tailwind's build process to create a subset of framework utility classes specific to your project, making it very important to understand how Tailwind decides which utility classes are included and how this process affects the use of utility classes in WordPress editor.

Finally, Tailwind's aggressive preflight (its CSS reset version) means that some parts of WordPress don't exactly fit the framework with its default settings.

Let's first look at what aspects of Tailwind work well in WordPress.

The aspect of Tailwind and WordPress working together

In order for Tailwind to run well without a lot of customization, it needs to act as the main CSS for a given page; this eliminates many use cases in WordPress.

For example, if you are building a WordPress plugin and need to include front-end CSS, then Tailwind's preflight will directly conflict with the active theme. Similarly, if you need to style the WordPress admin area (external to the editor), the management area's own style may be overwritten.

There are several ways to solve these two problems: you can disable preflight and prefix all utility classes, or you can add namespaces for all selectors using PostCSS. Either way, your configuration and workflow will become more complex.

However, if you are building a theme, Tailwind can be used directly. I have successfully created custom themes using classic editors and block editors, and I believe that as the site-wide editing matures, there will be many site-wide editing features working well with Tailwind.

In her blog post, “Gutenberg Site-wide Editors Don’t Have to Be Complete,” Tammie Lister describes Site-wide Editors as a standalone feature set that can be partially or fully adopted. Global style features for site-wide editing are unlikely to work with Tailwind, but many other features may.

So: You are building a theme, Tailwind is installed and configured, and you are adding a utility class with a smile. But will these utility classes work in WordPress editor?

Through planning, you can! Utility classes are available in the editor as long as you decide in advance which utility classes to use. You can't open the editor and use any and all Tailwind utility classes; Tailwind's emphasis on performance has built-in restrictions on the utility classes that only the topic uses, so you need to let Tailwind know in advance which utility classes are needed in the editor, even if they don't exist elsewhere in the code.

There are many ways to do this: you can create a safe list in the Tailwind configuration file; you can include comments containing the class list next to the code for the custom block you want to style with the block editor; you can even create just one file, list all editor-specific classes, and tell Tailwind to use it as one of the source files that it monitors the class name.

Determining ahead of time the editor class has never been a barrier to work for me, but this is still the most I've been asked about the relationship between Tailwind and WordPress.

Minimum WordPress theme with minimal Tailwind CSS integration

Let's start with the basic WordPress theme as possible. There are only two required files:

  • style.css
  • index.php

We will use Tailwind to generate style.css. For index.php, let's start with something simple:

 <?php /**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * Eg, it puts together the home page when no home.php file exists.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package WordPress
 * @subpackage Twenty_Twenty_One
 * @since Twenty Twenty-One 1.0
 */

get_header();
?>

<main id="site-content" role="main">

    <?php if ( have_posts() ) {

        while ( have_posts() ) {
            the_post();

            get_template_part( &#39;template-parts/content&#39;, get_post_type() );

        }

    } else {

        get_template_part( &#39;template-parts/content&#39;, &#39;none&#39; );

    }
    ?>

</main><!-- #site-content -->

<?php get_footer(); ?>
Copy after login

There are a lot of things WordPress themes should do, and the code above doesn't do it - like pagination, post thumbnails, using link elements instead of queueing stylesheets, etc - but that's enough to show a post and test if Tailwind works as expected.

In terms of Tailwind, we need three files:

  • package.json
  • tailwind.config.js
  • Tailwind's input file

You need npm before we proceed. If you are not used to using it, we have a guide to getting started with npm, which is a great place to start!

Since there is no package.json file yet, we will create an empty JSON file in the same folder as index.php by running the following command in the terminal:

 echo {} > ./package.json
Copy after login

With this file, we can install Tailwind:

 npm install tailwindcss --save-dev
Copy after login
Copy after login

And generate our Tailwind configuration file:

 npx tailwindcss init
Copy after login
Copy after login

In our tailwind.config.js file, we just need to tell Tailwind to search for utility classes in our PHP file:

 module.exports = {
  content: ["./**/*.php"],
  theme: {
    extend: {},
  },
  plugins: [],
}
Copy after login

If our theme uses Composer, we want to ignore the vendor directory, which can be done by adding something like "!**/vendor/**" to the content array. However, if all PHP files are part of the theme, the above will work!

We can name the input file whatever name we want. Let's create a file called tailwind.css and add the following to it:

 /*!
Theme Name: WordPress Tailwind
*/

@tailwind base;
@tailwind components;
@tailwind utilities;
Copy after login

The annotation at the top is necessary for WordPress to recognize the theme; three @tailwind directives add each layer of Tailwind.

That's it! We can now run the following command:

 npx tailwindcss -i ./tailwind.css -o ./style.css --watch
Copy after login
Copy after login

This tells the Tailwind CLI to use tailwind.css as input file to generate our style.css file. The --watch flag will continuously rebuild the style.css file when adding or removing utility classes from any PHP file in the project repository.

It's as simple as a Tailwind-powered WordPress theme, but it's unlikely that it's something you want to deploy to a production environment. So let's discuss some pathways to the production-ready topic.

Add TailwindCSS to an existing theme

There are two reasons why you might want to add Tailwind CSS to an existing theme that already has its own native CSS:

  • Experiment adding the Tailwind component to a styled theme
  • Convert theme from native CSS to Tailwind

We will demonstrate this by installing Tailwind in Twenty Twenty-One (the default theme for WordPress). (Why not Twenty Twenty-Two? The latest WordPress default theme is designed to show full-site editing and is not suitable for Tailwind integration.)

First, if the theme is not installed in your development environment, you should download and install it. After that, we only need to follow the following steps:

  • Navigate to the theme folder in the terminal.
  • Because Twenty Twenty-One already has its own package.json file, you can install Tailwind without creating a new file:
 npm install tailwindcss --save-dev
Copy after login
Copy after login
  • Add your tailwind.config.json file:
 npx tailwindcss init
Copy after login
Copy after login
  • Update your tailwind.config.json file to the same file as in the previous section.
  • Copy the Twenty Twenty-One existing style.css file to tailwind.css.

Now we need to add three @tailwind directives to the tailwind.css file. I suggest you construct the tailwind.css file as follows:

 /* WordPress theme file header is here. */

@tailwind base;

/* All existing CSSs are here. */

@tailwind components;
@tailwind utilities;
Copy after login

Putting the grassroots immediately after the topic title ensures WordPress continues to detect your topic, while also ensuring that the Tailwind CSS reset appears in the file as early as possible.

All existing CSSs are located behind the base layer, making sure these styles take precedence over resets.

Finally, the component and utility layers are immediately followed, so they can take precedence over any CSS declaration with the same specificity.

Now, like our minimal topic, we will run the following command:

 npx tailwindcss -i ./tailwind.css -o ./style.css --watch
Copy after login
Copy after login

Now that your new style.css file is generated every time you change the PHP file, you should check for subtle rendering differences between the modified theme and the original theme. These are caused by Tailwind's CSS reset, which is a little more thorough than some themes might expect. For Twenty Twenty-One, the only modification I made is to add text-decoration-line: underline to the a element.

After solving the rendering problem, let's add the Header Banner component from the Tailwind UI (Tailwind's first-party component library). Copy the code from the Tailwind UI website and paste it after the "Jump to Content" link in header.php:

very good! Since we are now going to use utility classes to overwrite some existing higher specificity classes built into the topic, we will add a line to the tailwind.config.js file:

 module.exports = {
  Important: true,
  content: ["./**/*.php"],
  theme: {
    extend: {},
  },
  plugins: [],
}
Copy after login

This marks all Tailwind CSS utilities as !important so that they can override existing classes with higher specificity. (I never set important to true in production environment, but if I'm converting a website from native CSS to Tailwind, I almost certainly do it.)

By adding a quick no-underline class to the Learn More link and adding bg-transparent and border-0 to the close button, we're done:

It looks a bit harsh to see the components of the Tailwind UI merge into the WordPress default theme, but this is a nice demonstration of the Tailwind components and their inherent portability.

Start from scratch

If you use Tailwind to create a new topic, your process will be very similar to the minimum example above. Instead of running the Tailwind CLI directly from the command line, you might want to create separate npm scripts for development and production builds and monitor changes. You may also want to create a separate build for the WordPress editor.

If you're looking for a starting point beyond the smallest example above - but not beyond the extent that it itself has its self-righteous style - I've created a Tailwind-optimized WordPress theme generator inspired by Underscores (_s), once a canonical WordPress launch theme. Named _tw, this is a quick start I hope to have when I first used Tailwind with WordPress. It is still the first step in all my client projects.

If you're willing to further deviate from the structure of a typical WordPress theme and add Laravel Blade templates to your toolkit, Sage is a great option and they have a setup guide for Tailwind to help you get started.

Regardless of how you choose to start, I encourage you to take some time to adapt to Tailwind CSS and use utility classes to style HTML documents: it may feel unusual at first, but you will soon find yourself taking on more client work than you used to because you build your website faster than you used to — and hopefully, like me, more fun in doing it.

The above is the detailed content of Adding Tailwind CSS to New and Existing WordPress Themes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template