Why tailwind?
Adding Tailwind to my workflow has been the biggest productivity boost I've ever seen. In the past I used Bootstrap to develop the front end of my WordPress themes, using its components and then changing the styles in another CSS file.
The latest versions of Bootstrap allow us to change the variables used to generate the CSS, but in my opinion this is the slower option in terms of productivity.
The CSS file that Tailwind produces has an amazingly small file size, averaging <150KB in my experience, and the best part? The file only contains CSS classes that you actually used.
Unlike other CSS frameworks that are component based, you don't have hundreds of classes that are never used anywhere in your design. If you use frameworks such asBootstrapIn the past, you'll immediately notice Tailwind's undescribed approach. This is one of its most powerful features and the real reason many of us are drawn to using it. This undescribed approach allows us, as developers, to create a truly unique design without being locked into a framework like Bootstrap's aesthetic feel.
It's worth noting that Tailwind offers aCDN approach, but that's just not suitable for a production environment. The CDN version includes all helper classes included in the framework and includes a massive amount of bloat, meaning we lose any performance improvements we gained by switching to Tailwind.
This article aims to show you how to set up Tailwind to work with WordPress, allowing Tailwind to do what it does best without changing the default WordPress behavior. With the minimal setup example in this post, you can customize the environment to suit your needs.
Install Tailwind and required packages
First we need to install the required packages from NPM if you don't already have themPackage.jsonfile in your project, you can create one by running itnpm-Initin the terminal withNode.jsFurnished.
The following command will install all the packages we need for development. If you are new to using NPM packages, thenode_modulesThe directory is used for development only and will not be carried over to production with the rest of your design. The code we need from these packages is simply used by Tailwind's build step and is not required for production.
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest postcss-cli@latest @tailwindcss/typography
configuration file
Now we need to create the configuration file that Tailwind will use to identify files in our theme that it needs to monitor in order to regenerate its CSS file. This file is used to change the plugins Tailwind will use and the theme options like the color palette, more on that later in this article.
To get started, runnpx tailwindcss initor create a file namedtailwind.config.jsin the root of your theme and add the following content.
module.exports = { Inhalt: [./template-parts/**/*.php“, „./*.php“, „./js/*.js“ ],Theme: {extend: {}, },plugins: [ require('@tailwindcss/typography') ],}
The last configuration file we need is the PostCSS configuration file, which controls the setting for the PostCSS CSS preprocessor that we use. Create a file namedpostcss.config.js.
module.exports = {plugins: {'tailwindcss': {},'autoprefixer': {},} }
Setting up the CSS file
We need to add Tailwind's directives to our CSS file so Tailwind can add the CSS to our output CSS file. Add the following to yours at the top./css/style.cssFile. Each of the instructions adds one of Tailwind's layers.
@tailwind Base; @tailwind Components; @tailwind Utilities;
Set up the watch command
In order for us to start the JIT compiler, we need an NPM script that tells Tailwind where to output the final CSS. We do this by adding an element toscriptsblock thePackage.jsonFile.
"scripts": {"watch": "npx postcss ./css/style.css -o ./css/style.min.css --watch"}
Now we're ready to go! Run thosenpm Laufuhrcommand and Tailwind will start compiling to the output CSS file. Running this command will start a process in the terminal that you should keep running while you develop the design. When saving the in thetailwind.config.jsfile, Tailwind reads the classes you use and adds or removes them from the final CSS file.
npm Laufuhr
Queue the output CSS in WordPress
The./css/style.cssFile is our developer file only, this should not be loaded on the frontend. Thestyle.min.cssFile should be loaded instead.
add_action('wp_enqueue_scripts', function(){ wp_enqueue_style('theme-css', get_stylesheet_directory_uri() . '/css/style.min.css');});
As you develop your theme, I recommend adding a version parameter to your asset enqueue function to force the browser to use a new version of the file each time it is updated. You can do this by addingTime()to the 4th parameter of the function.
add_action('wp_enqueue_scripts', function(){ wp_enqueue_style('theme-css', get_stylesheet_directory_uri() . '/css/style.min.css', [], time());});
Styling-Content von Guttenberg
Since the content in the admin post editor isn't monitored by Tailwind, we have two choices. We can either use the safe lists feature, which allows us to add a list of classes that we want Tailwind to always include in our final CSS output, or we can use the typography plugin we installed at the beginning of this article.
Option A - Typografie-Plugin
The typography plugin has already been set up if you followed this article. Implementation is as simple as adding theProseclass to wrapper ourthe content()Financial support.
<div class="prose"> <?php the_content(); ?></div>
What does "prose" do?
Proseis a class that targets all child elements and styles them as the browser would before Tailwind resets the user-agent style sheet. With theProseClass, we can target segments of our theme that come from the backend, whether it's WISYWIG editors or the Gutenberg editor.
You should be aware of thisProseQuite a few changes are made, including the font color, so you'll want to go through the resulting styling with a fine-toothed comb and make sure the design still follows your brand guidelines or your theme.
change prose styles
You can change any part of the stylesProseClass applies with the following syntax:
<div class="prosa prose-p:text-red-500"> <?php the_content(); ?></div>
This will turn all paragraph tags red. Since this can become a huge list of classes when trying to tailor your blog posts to your topic, I prefer to just assign the prose classes to oneblog contentClass as seen here
.blog-content { @apply prosa w-full max-w-full prosa-li:marker:text-primary prosa-img:w-full prosa-headings:mt-4 prosa-h2:text-4xl;}
Adding this snippet to your CSS file allows Tailwind to create ablog contentClass with all these styles in it.
WordPress CSS overrides tailwind
WordPress still loads its own Styles CSS file, which overrides some of the Tailwind classes due to the use of the !important directive in the WordPress CSS. For pages without the use of Gutenberg blocks, I recommend you to dequeue the style files loaded by WordPress, including the list of CSS variables with colors. You can do this by adding the following to yoursfunctions.phpFile that disables WordPress CSS files on the homepage and archive pages, other conditions for disabling the if statement can be added, such as:if_single('post')Disable the WordPress style in blog posts, although this is not recommended as the end user actually uses the Gutenberg blocks in this context. You canLearn more about disabling WordPress' CSS filesin my article on WordPress performance.
add_action( 'wp_enqueue_scripts', function () { if ( is_front_page() || is_home() || is_archive() ) { wp_dequeue_style( 'global-styles' ); wp_dequeue_style( 'wp-block-library' ); wp_dequeue_style( ' wp-block-library-theme' ); }}, 100 );
Prosa Browser Compatibility
The Typography Tailwind Plugin uses the:Wo()Selector not supported by any Internet Explorer version and only version 88+ for Chromium browsers. For a full list of browser support, you canCheck out the "where" selector on caniuse.com.
Option B - Safelist and writing styles manually
Option one is a tedious task, and you can often miss out on the classes you need if you do this. However, if you want full control over which classes appear in your final CSS file, then this option is the way to go.
Defining the safe list
Defining the safe list is as simple as adding an array to ittailwind.config.jsfile we created earlier.
safelist: [ 'bg-red-500', 'text-3xl', 'lg:text-4xl',],
The settings block shown above takes care of thisbg-rot-500,text-3xlAndlg:text-4xlare always added to the CSS file, regardless of whether they have been used or not.
You should keep this method in mind for future theme development, as you may come across a situation where you need to allow a class from Gutenberg or a WISYWIG editor to be used once in the final output for a specific piece of content.
Writing the styles manually
Since Tailwind cannot apply styles to the HTML created by Guttenberg or a WISYWIG editor, we have to apply the styles ourselves, which we can do with the help of@useDirective in our CSS file, which then adds the style rule to our final CSS file without having to use it in any of the files Tailwind watches.
This can be a tedious approach and can become a mess when you've built up a collection of blog posts with a variety of styles.
.blog-content h2 { @apply text-3xl font-bold mt-8 mb-4;}
Tailwind and template parts
Using template parts with Tailwind is a game changer and works best when combined with the templating feature that WordPress offers. For most applications, page templates should consist of individual template parts, which then consist of additional templates.
Not only does this allow us to keep our code DRY, but it also allows us to focus on the classes that control the styling of specific elements on the final page - having huge chunks of HTML with a dozen classes can quickly become complicated cause the problem you are looking for.
Adding styles to WordPress menus with Tailwind example
WordPress generated navigation menus are a bit more difficult to use as they spit out HTML without caring about your front-end stack. The solution to this is to use@useDirective and style of the classes WordPress uses for its menus.
This is my first stop for designing WordPress menus that you can use as a starting point for your navigation menus.
<nav class="list-none pt-2 hidden lg:flex"> <?php wp_nav_menu( array( 'theme_location' => 'header-menu', 'fallback_cb' => false, 'container' => false, ' items_wrap' => '<ul id="%1$s" class="%2$s flex items-center text-sm xl:text-base space-x-4 xl:space-x-8 font-bold" >%3$s</ul>', ) ); ?></nav>
.menu li { display: block;}.menu li:not(.menu-item-has-children) a { display: block;}.menu .menu-item-has-children { position: relative;}@media ( Mindestbreite: 1024px) { .menu .menu-item-has-children ul.sub-menu { @apply absolute bg-white pt-6 pb-3 px-3 shadow-2xl min-w-[200px] left- 0 rand-b rand-b-grau-200 z-10 übergang-alles dauer-200 lockern-raus übersetzen-y-5 opacity-0 zeiger-ereignisse-none; }}.menu .menu-item-has-children ul.sub-menu li { @apply w-full;}@media (max-width: 1024px) { .menu .menu-item-has-children ul.sub- Menü li {Rand oben: 0,75 rem; }}.menu .Menüelement-hat-Kinder ul.sub-menu ul.sub-menu { left: unset; Polsterung oben: 0,75rem; rechts: calc(100% + 0.1rem); oben: -0,7 rem; box-shadow: unset;}@media (max-width: 1024px) { .menu .menu-item-has-children ul.sub-menu ul.sub-menu { padding-top: 0; Textausrichtung: Mitte; }}@media (max-width: 1024px) { .menu .menu-item-has-children ul.sub-menu { text-align: center; }}.menu .menu-item-has-children:hover > ul.sub-menu { @apply flex translate-y-0 opacity-100 pointer-events-auto}
Styling WordPress pagination with tailwind example
Similar to the problems caused by WordPress generated navigation menus, the WordPress generated pagination HTML contains unused classes so we need to use those@useinstruction to style it.
.pagination { @apply flex justify-center;}.pagination .nav-links { @apply flex mx-auto space-x-3 items-center;}.pagination .nav-links a, .pagination .nav-links span { @apply block text-center py-0.5 bg-transparenter text-schwarze übergangsfarben dauer-100ease-in-out;}.pagination .nav-links a.current, .pagination .nav-links span.current { @apply bg -red-400 text-white;}.pagination .nav-links a:not(.next):not(.prev), .pagination .nav-links span:not(.next):not(.prev) { @ w-[30px] anwenden hover:bg-opacity-80 Rand gerundet-voller Rand hover:border-red-400;}
Separate CSS components
When your subject gets more complex when you design things like thatblog contentthe class mentioned above and the pagination/navigation features can make your CSS file cluttered. To solve this problem, you can create standalone CSS files that contain the styles for the relevant component and use PostCSS's import directive to allow PostCSS to compile these files into the one final CSS final that we use for the production will use.
Installing the PostCSS import plugin
To do this we need to install itPostcss-ImportPlugin and upload it to ourpostcss.config.jsFile.
npm install -D postcss-import
module.exports = { plugins: { 'postcss-import': {}, 'tailwindcss': {}, 'autoprefixer': {} },};
Import standalone CSS files
Now we can import our standalone CSS files into our final output!
@tailwind Base;@tailwind Components;@tailwind Utilities;@import './wp-nav-menu-styles';@import './wp-pagination-styles';@import './blog-content- styles';
Generating the color palette for your WordPress theme
For example, as you most likely noticed, Tailwind allows us to use colors with multiple shadestext-root-300would be a lighter shade of red. But what about our brand colors/policies? We can't just pick the color that comes closest to Tailwind.
To solve this problem, Tailwind allows us to expand its color palette and even override the default colors. With tools likeDownwind ShadowWe can input our brand colors and generate JSON with shades of that color. Below is an example with#F97316.
'orange': { STANDARD: '#F97316', '50': '#FEDFC9', '100': '#FDD3B5', '200': '#FCBB8D', '300': '#FBA366', '400 ': '#FA8B3E', '500': '#F97316', '600': '#D25905', '700': '#9B4204', '800': '#642B03', '900': '#2D1301 '},
As you can see the shadow500is the default color, and we can use the color with no shade specified (bg-orange)
To include this in Tailwind you need to change theThemeblock thetailwind.config.jsconfig file, here you can add as many colors as your theme dictates here.
You can use thoseFunction for any stylefrom Tailwind v3 to use such unique colorstext-[#f7f7f7].
Theme: { Expand: { Colors: { 'Orange': { DEFAULT: '#F97316', '50': '#FEDFC9', '100': '#FDD3B5', '200': '#FCBB8D', '300 ': '#FBA366', '400': '#FA8B3E', '500': '#F97316', '600': '#D25905', '700': '#9B4204', '800': '#642B03 ', '900': '#2D1301' }, } },},