Open In App

Tailwind CSS 3 Classes doesn’t Override Previous Classes

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Tailwind CSS is basically a Utility-first CSS framework for building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. Also, it is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS.

Syntax

<div class="bg-blue-500 text-white">
    Blue Background
</div>

Approaches

Tailwind CSS is designed to be a low-level utility-first framework, which means that classes are not automatically overridden by default. To work effectively with Tailwind CSS, consider the following approaches:

  • Specificity Matters: CSS classes in Tailwind CSS have specific levels of specificity. Classes with higher specificity will override those with lower specificity. This is particularly important when you encounter conflicts. For example, classes like hover:bg-blue-700 have higher specificity than bg-blue-500, so they will override the background color on hover.
  • Use Utility Classes Smartly: Tailwind CSS provides a wide range of utility classes, including hover, focus, and active variants. Utilize these variants to modify styles when specific interactions occur. For instance, to change the background color of a button on hover, use hover:bg-blue-700 rather than just bg-blue-500.

Example 1: This example illustrates the overriding of the Background Color in Tailwind CSS.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <link href=
          rel="stylesheet">
    <title>Tailwind CSS Example</title>
</head>
  
<body>
    <div class="bg-blue-500 p-4">
        <p class="bg-red-500 text-white">
            Red background with white text
        </p>
    </div>
</body>
  
</html>


Output:

aa

Example 2: This example illustrates the Text Color Override with Hover Effect in Tailwind CSS.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, 
                   initial-scale=1.0">
    <link href=
          rel="stylesheet">
    <title>Tailwind CSS Example</title>
</head>
  
<body>
    <p class="bg-yellow-200 text-blue-500 
              hover:bg-yellow-400 
              hover:text-green-500 p-4 
              rounded-lg">
        Blue text on yellow background
    </p>
    <p class="bg-pink-200 text-blue-500 
              hover:bg-pink-400 
              hover:text-red-500 
              p-4 rounded-lg">
        Blue text on pink background
    </p>
</body>
  
</html>


Output:

Tailwind-CSS-Example---Google-Chrome-2023-09-26-16-19-12



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads