Adding Tailwind CSS to New and Existing WordPress Themes
Mar 13, 2025 pm 01:00 PMSince 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( 'template-parts/content', get_post_type() ); } } else { get_template_part( 'template-parts/content', 'none' ); } ?> </main><!-- #site-content --> <?php get_footer(); ?>
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
With this file, we can install Tailwind:
npm install tailwindcss --save-dev
And generate our Tailwind configuration file:
npx tailwindcss init
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: [], }
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;
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
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
- Add your tailwind.config.json file:
npx tailwindcss init
- 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;
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
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: [], }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
