Creating Custom Utility Classes Using ‘@layer’ directive

  • Integrate Tailwind CSS for efficient styling.
  • Use layer directive to implement your custom styling in index.css file.
  • We have made three buttons with style including small button, medium button, and large button with some styling including background color, text color, rounded corners, height, and width.

Example: Illustration of Creating Custom Utility Classes in Tailwind CSS and React JS using the ‘@layer’ directive

CSS




/* index.css */
 
@tailwind base;
@tailwind components;
@tailwind utilities;
 
 
@layer utilities {
  .btn-blue-sm {
    @apply bg-blue-500 text-white text-xs w-24 h-12 rounded;
  }
  .btn-blue-md {
    @apply bg-blue-500 text-white font-bold text-xs h-16 px-4 rounded;
  }
  .btn-blue-lg {
    @apply bg-blue-500 text-white font-bold py-6 px-4 rounded;
  }
}


Javascript




// App.js
 
function App() {
  return (
    <div className="App p-12">
          <h1 className='tracking-wide text-gray-600 text-3xl font-bold'>Custom Utility Colors Using Tailwind `extend`</h1>
          <div className='mt-12 flex justify-center gap-12'>
            <div><button className='btn-blue-sm'>Small Button</button></div>
            <div><button className='btn-blue-md'>Medium Button</button></div>
            <div><button className='btn-blue-lg'>Large Button</button></div>
          </div>
    </div>
  );
}
 
export default App;


Steps to run the application:

Step 1: Type the following command in the terminal.

npm start

Step 2: Open the web browser and type the following URL

http://localhost:3000/

Output:

Output



Creating Custom Utility Classes in Tailwind CSS and React JS

Tailwind CSS empowers development with a variety of utility classes out of the box, helping us in rapid development and consistent styling. However, In some scenarios, you might want to implement your custom styling.

We will discuss the following approaches to create Custom Utility Classes in Tailwind and React.

Table of Content

  • Creating Custom Utility Classes Using Tailwind ‘Extend’ Option
  • Creating Custom Utility Classes Using ‘@layer’ directive

Similar Reads

Steps to Create a React App and Installing Required Module

Step 1: Create a new react application and enter it into the directory by running the following commands in the terminal...

Folder Structure:

Project Structure...

Creating Custom Utility Classes Using Tailwind ‘Extend’ Option

Integrate Tailwind CSS for efficient styling. We have made four boxes using

Creating Custom Utility Classes Using ‘@layer’ directive

...

Contact Us