Don’t get left behind! Sign up to the WebDevEducation newsletter for free tutorials, coupon codes, and more! 🎉




    tailwind css wordpress

    Using Tailwind CSS in WordPress blocks

    In my previous post, I stated that I have a reignited love for Tailwind CSS. I felt this way after using “normal” CSS again while developing custom blocks in WordPress. It was a frustrating experience which made me realise; I friggin love Tailwind CSS. In this post, I’m going to show you one possible method to use Tailwind CSS for WordPress block development.

    Set up Tailwind CSS in WordPress

    Getting set up with Tailwind CSS in WordPress isn’t super straightforward. Assuming you set up your WordPress block plugin using:

    npx @wordpress/create-block

    You can add tailwind with the following commands:

    npm install -D tailwindcss
    npx tailwindcss init

    This will create a tailwind.config.js, which we can modify to scan files that may contain Tailwind CSS classes. In our case, we want to scan the src directory and any decendant directories, for html, php, and js files that may contain Tailwind CSS classes:

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: ["./src/**/*.{php,html,js}"],
      theme: {
        extend: {},
      },
      plugins: [],
    }

    Then we need to add the @tailwind directives for each of Tailwind’s layers to a global CSS file:

    @tailwind base;
    @tailwind components;
    @tailwind utilities;

    Then we need to set up a build process. We can do that by adding new scripts to package.json:

    "scripts": {
        "tailwind:build": "npx tailwindcss -i ./src/input.css -o ./build-assets/index.css",
        "tailwind:watch": "npm run tailwind:build -- --watch"
    }

    This will output our final css build to a directory called build-assets/index.css. From here, we need to update our start and build scripts to use these new Tailwind build processes:

    "scripts": {
        "build": "wp-scripts build --webpack-copy-php && npm run tailwind:build",
        "start": "wp-scripts start --webpack-copy-php & npm run tailwind:watch"
    }

    Finally, we need to reference the ouput css file from within block.json:

    "style": ["file:../build-assets/index.css", "file:./style-index.css"]

    Interested in learning more about Tailwind CSS?

    Tailwind CSS zero to hero course

    Want to go from zero to hero with Tailwind? Take the Tailwind CSS Zero to Hero course!


    Posted

    in

    ,

    by