Tutorials & Guides
How to Build a Local CLI Tool to Convert Legacy CSS to Tailwind Utility Classes with Claude 3.5 Sonnet
Ditch the stylesheet soup. Build a lightweight Python CLI tool that uses Claude 3.5 Sonnet to parse your legacy CSS files and refactor your HTML elements into modern Tailwind utility classes.
Updated 11/23/2026
Let's be honest: nobody actually enjoys digging through a legacy stylesheet from 2018. It is usually a fragile mountain of nested media queries, redundant margin declarations, and highly questionable naming conventions. If you are migrating an old project to Tailwind CSS, manually translating those ancient styles into utility classes is a recipe for a migraine.
Sure, you could copy and paste your HTML and CSS blocks back and forth into a web UI, but that is a massive waste of time. Instead, we can build a local CLI tool that automates this entire headache.
In this guide, we will build a lightweight Python CLI tool that takes a legacy CSS file and an HTML template, sends them to Claude 3.5 Sonnet, and outputs clean, refactored HTML using modern Tailwind utility classes. It will even strip out the redundant style tags for you.
What Makes this Tool Tick
What makes this utility tick is its ability to handle style context without losing semantic layout. Unlike dumb regex parsers, Claude understands the intent behind your CSS rules. If you have a custom class called .btn-primary-gradient that applies a linear gradient, border-radius, and transitions, Claude can instantly translate that into the equivalent Tailwind layout, spacing, and colour utility classes.
To make this happen, our CLI will: 1. Accept an HTML file and a CSS file as inputs. 2. Package them together with a carefully designed context prompt. 3. Send them to the Anthropic API. 4. Save the refactored HTML to a new file, leaving your original files untouched.
Which AI should I use for this?
Tickd is independent and not affiliated with any AI company.
Prerequisites
Before we write any code, make sure you have the following ready: - Python 3.8 or higher installed on your machine. - An Anthropic API key. If you run into issues setting up your environment or authentication, you can check out our Claude troubleshooting hub.
Let’s start by setting up our project directory and installing the required dependency:
`bash
mkdir css-to-tailwind-cli
cd css-to-tailwind-cli
pip install anthropic
`
Set your API key in your terminal session:
`bash
export ANTHROPIC_API_KEY="your-api-key-here"
`
Step 1: Crafting the Refactoring Prompt
The secret to reliable structured output from an LLM is a strict prompt system. We want Claude to perform the conversion without wrapping the output in conversational fluff or unnecessary markdown code blocks that break script execution.
If you want to tweak this prompt structure or test different styling outputs, you can always run it through our prompt generator first.
Here is the system prompt we will embed in our script:
`text
You are an expert front-end developer specialising in Tailwind CSS migrations.
Your task is to take a piece of raw HTML and its corresponding legacy CSS, and rewrite the HTML to use Tailwind CSS utility classes instead of the legacy CSS classes.
Strict Rules:
1. Replace all legacy class names on HTML elements with their exact Tailwind CSS equivalents.
2. Resolve custom CSS properties (variables) if they are provided in the stylesheet.
3. Maintain the exact semantic structure, text content, and attributes of the original HTML.
4. Do not include any legacy external CSS link tags or inline <style> tags in the final output.
5. Output ONLY the raw, refactored HTML. Do not wrap the output in markdown code blocks (e.g., do not write `html). No explanations, no introductory text, no pleasantries.
`
Step 2: Writing the Python CLI Script
Create a new file named converter.py in your project folder. We will use Python’s built-in argparse library to handle the command-line arguments and the anthropic SDK to manage our API calls.
`python
import os
import sys
import argparse
from anthropic import Anthropic
def main(): # 1. Parse command line arguments parser = argparse.ArgumentParser( description="Convert legacy HTML and CSS into Tailwind-optimised HTML using Claude 3.5 Sonnet." ) parser.add_argument( "--html", required=True, help="Path to the input HTML file." ) parser.add_argument( "--css", required=True, help="Path to the legacy CSS file containing matching styles." ) parser.add_argument( "--output", required=True, help="Path where the refactored HTML should be saved." ) args = parser.parse_args()
2. Check for Anthropic API Key if not os.environ.get("ANTHROPIC_API_KEY"): print("Error: ANTHROPIC_API_KEY environment variable is not set.", file=sys.stderr) sys.exit(1)
3. Read input files try: with open(args.html, 'r', encoding='utf-8') as html_file: html_content = html_file.read() except Exception as e: print(f"Error reading HTML file: {e}", file=sys.stderr) sys.exit(1)
try: with open(args.css, 'r', encoding='utf-8') as css_file: css_content = css_file.read() except Exception as e: print(f"Error reading CSS file: {e}", file=sys.stderr) sys.exit(1)
print("⌛ Sending assets to Claude 3.5 Sonnet for conversion...")
4. Initialize client and call the API client = Anthropic()
system_prompt = ( "You are an expert front-end developer specialising in Tailwind CSS migrations.\n" "Your task is to take a piece of raw HTML and its corresponding legacy CSS, and rewrite the HTML to use Tailwind CSS utility classes instead of the legacy CSS classes.\n\n" "Strict Rules:\n" "1. Replace all legacy class names on HTML elements with their exact Tailwind CSS equivalents.\n" "2. Resolve custom CSS properties (variables) if they are provided in the stylesheet.\n" "3. Maintain the exact semantic structure, text content, and attributes of the original HTML.\n" "4. Do not include any legacy external CSS link tags or inline <style> tags in the final output.\n" "5. Output ONLY the raw, refactored HTML. Do not wrap the output in markdown code blocks. No explanations, no introductory text, no pleasantries." )
user_content = f"Legacy CSS:\n\n{css_content}\n\nOriginal HTML:\n\n{html_content}"
try: response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=4000, temperature=0.1, # Low temperature ensures deterministic, accurate mapping system=system_prompt, messages=[ {"role": "user", "content": user_content} ] ) # Extract output text refactored_html = response.content[0].text.strip() except Exception as e: print(f"Error communicating with Anthropic API: {e}", file=sys.stderr) sys.exit(1)
5. Save the output try: with open(args.output, 'w', encoding='utf-8') as out_file: out_file.write(refactored_html) print(f"🎉 Refactored HTML successfully written to: {args.output}") except Exception as e: print(f"Error writing output file: {e}", file=sys.stderr) sys.exit(1)
if __name__ == "__main__":
main()
`
Step 3: Testing the Tool
Let’s run a quick local test to see how well Claude maps custom CSS classes to Tailwind utility classes. Create two sample files in your working directory.
First, a legacy CSS file named style.css:
`css
.card {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
padding: 24px;
max-width: 400px;
margin: 16px auto;
}
.card-title { font-size: 20px; font-weight: 700; color: #1a202c; margin-bottom: 8px; }
.card-body { font-size: 14px; color: #4a5568; line-height: 1.5; }
.btn { display: inline-block; background-color: #3182ce; color: white; padding: 10px 20px; border-radius: 4px; text-decoration: none; font-weight: 600; margin-top: 16px; transition: background-color 0.2s; }
.btn:hover {
background-color: #2b6cb0;
}
`
Next, a matching HTML file named index.html:
`html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<title>Legacy Card Component</title>
</head>
<body>
<div class="card">
<h2 class="card-title">Tailwind Migration</h2>
<p class="card-body">
This legacy card component needs to be converted into modern utility classes.
</p>
<a href="#" class="btn">Get Started</a>
</div>
</body>
</html>
`
Now, run your new CLI tool to generate the Tailwind-compatible version:
`bash
python converter.py --html index.html --css style.css --output index-tailwind.html
`
Within a few seconds, you should see index-tailwind.html appear. Open it up, and you will find that Claude has completely refactored your document:
`html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Legacy Card Component</title>
</head>
<body>
<div class="bg-white rounded-lg shadow-md p-6 max-w-[400px] my-4 mx-auto">
<h2 class="text-xl font-bold text-gray-900 mb-2">Tailwind Migration</h2>
<p class="text-sm text-gray-600 leading-relaxed">
This legacy card component needs to be converted into modern utility classes.
</p>
<a href="#" class="inline-block bg-blue-600 text-white px-5 py-2.5 rounded font-semibold mt-4 hover:bg-blue-700 transition-colors duration-200 no-underline">Get Started</a>
</div>
</body>
</html>
`
Managing API Limits and Long Files
If you are planning to run this tool over massive production templates with thousands of lines of code, keep these two tips in mind:
- Token Budgets: If your HTML file is incredibly large, it can easily approach Anthropic's token output limits. For very complex structures, process the HTML in chunks (like individual modular components or partial views) rather than feed in a single 5,000-line master page.
- Unused CSS: Do not feed your entire global legacy stylesheet into Claude if you are only refactoring a tiny page element. Crop the CSS file to match the styles used on the target component. It keeps token usage down, costs lower, and speeds up the response time.
With this tool in your CLI arsenal, you can easily shift legacy projects into clean Tailwind markups in seconds. Grab the script, drop it in your local dev folder, and stop writing inline styling by hand.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.