A Python utility for merging Tailwind CSS class lists intelligently, resolving conflicts based on Tailwind's principles. Inspired by the popular tailwind-merge JavaScript package.
This utility ensures that when you combine multiple strings of Tailwind classes (e.g., from different component states or logic branches), the resulting string is clean, minimal, and applies the intended styles by removing redundant or conflicting classes based on their function.
Using pip:
pip install tailwind-merge
from tailwind_merge import TailwindMerge
# Initialize
twm = TailwindMerge()
result = twm.merge(
"p-4 w-6 text-blue-500", # Initial classes
"w-8 text-red-500" # Overrides for width and text color
)
# "p-4 text-red-500 w-8"
result = twm.merge("pl-4", "pr-6 pl-2")
# "pl-2 pr-6"
result = twm.merge("p-2 hover:p-4", "p-3")
# "hover:p-4 p-3"
result = twm.merge("hover:p-2", "focus:p-1 hover:p-4")
# "hover:p-4 focus:p-1"
result = twm.merge("p-1", "p-[2px]")
# "p-[2px]"
result = twm.merge(
"flex items-center justify-center", # Base layout
"justify-between", # Override justify
"text-red-500", # Add text color
"hover:text-blue-500 text-lg" # Add hover color and text size
)
# "flex items-center justify-between text-red-500 hover:text-blue-500 text-lg"
twm.add_rule('custom-icon-size', ['icon-sm', 'icon-md', 'icon-lg'])
twm.merge("icon-sm icon-lg")
# "icon-lg"
hover:
, focus:
, md:
, dark:
, etc.). Conflicts are resolved independently for base styles and each unique modifier combination (e.g., hover:text-red-500
conflicts with hover:text-green-500
but not with focus:p-4
or p-4
).p-[3px]
, w-[calc(100%-theme(spacing.4))]
, text-[#FF0000]
).border-t-2
as belonging to border-width-top
before matching the shorter border-
prefix).add_rule
method for project-specific utilities or third-party libraries.Contributions are welcome! If you find a bug, have a feature request, or want to improve the class definitions, please feel free to open an issue or submit a Pull Request. Ensure tests pass and consider adding new tests for your changes.