Today we are going to talk about Tailwind CSS which is a utility-first CSS framework that allows you to create custom designs without even leaving your HTML. We’ll be creating reusable plugins, which are a great way to add new styles and extend Tailwind CSS using JavaScript. Let’s start!
Plugins allow you to add new styles and utilities to Tailwind CSS that aren’t included automatically. This is very useful if you need certain styles for your project or want to re-use custom styles across several projects. You can customize Tailwind CSS by creating plugins that add new utility classes, component styles, or even variants. This makes Tailwind CSS incredibly powerful for web development.
First of all, you must import the plugin function from tailwindcss/plugin
. This function allows you to inject new styles which you want to create with Tailwind CSS into your stylesheet using CSS-in-JS syntax.
const plugin = require('tailwindcss/plugin');
Now we should call imported plugin
function, it accepts an anonymous function as first argument. Within this function, you can set your own styles.
Here's an example of a simple plug-in that enables you to add a new background gradient utility:
// myPlugin.js
const plugin = require('tailwindcss/plugin');
module.exports = plugin(function({ addUtilities }) {
addUtilities({
'.bg-gradient': {
background: 'linear-gradient(to right, #ff7e5f, #feb47b)',
},
});
});
In above code example, we used the addUtilities
function to add a new utility class called .bg-gradient. This class applies a linear gradient background to any element it is added to. The Tailwind plugin API offers a range of de-structured helper functions that are used as the first argument of the plugin
function.
After successfully your plugin has been created you have to now declare it in the Tailwind CSS config file (tailwind.config.js
) inside the plugins
array:
// tailwind.config.js
module.exports = {
content: [
'./src/**/*.{html,js}',
],
theme: {
extend: {},
},
plugins: [
require('./src/myPlugin'),
],
}
After adding plugin into the Tailwind CSS config, the background gradient class can be used in your HTML as shown below:
<!-- index.html -->
<div class="bg-gradient text-5xl p-16">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto non possimus rerum hic animi natus
consectetur exercitationem. Quam magnam, obcaecati maiores dolor tempore excepturi nulla perferendis fuga
ut, provident est?
</div>
Here is how it looks;
Creating reusable plugins for Tailwind CSS is a great way to extend its functionality and customise it to your project needs. So, go ahead, create your plugins and see your projects explode with awesome and special styles!
Happy coding! 🚀💻
Explore top free Next.js landing page templates from sbthemes. Fast, responsive, and customizable for any web app or project.
No Spam. Only high quality content and updates of our products.
Join 20,000+ other creators in our community