레거시 CSS와 함께 사용하기
레거시 CSS 또는 다른 프레임워크가 있는 기존 프로젝트에 Tailwind를 통합하고, 우선순위 충돌을 관리하면서 점진적으로 마이그레이션합니다.
레거시 CSS와 함께 사용하기은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Coexistence Challenge
Many real-world projects cannot rewrite all existing styles at once. You might inherit a project using Bootstrap, a homegrown CSS framework, or thousands of lines of plain CSS. Introducing Tailwind into such a project means both systems must coexist without breaking each other. Understanding specificity, class naming collisions, and layer ordering is essential for a smooth incremental migration.
Understanding CSS Specificity Conflicts
Tailwind utilities use single-class selectors with specificity 0,1,0. Legacy CSS often uses descendant selectors like .header .nav a with higher specificity. When both styles target the same element, the higher-specificity legacy rule wins regardless of source order. This means a Tailwind utility like text-blue-600 may appear to do nothing if a legacy descendant rule overrides it.
/* Legacy CSS — specificity 0,2,1 */
.header .nav a {
color: #333333;
}
/* Tailwind utility — specificity 0,1,0 */
/* .text-blue-600 { color: #2563eb; } */
<!-- This Tailwind class LOSES because legacy has higher specificity -->
<header class="header">
<nav class="nav">
<a class="text-blue-600">Will still be #333333</a>
</nav>
</header>Using @layer to Manage Specificity
Tailwind's @layer directive places rules inside CSS Cascade Layers. Styles in @layer base and @layer utilities have lower priority than unlayered (legacy) styles, even if the utility has the same specificity. This means legacy styles naturally win without needing !important. Conversely, new Tailwind utilities you add via @layer utilities will not accidentally break the existing CSS.
/*
Order of precedence (highest to lowest):
1. !important declarations
2. Unlayered styles (legacy CSS)
3. @layer utilities
4. @layer components
5. @layer base
Legacy CSS in a separate file wins by default over Tailwind layers.
*/
/* legacy.css — unlayered, wins over Tailwind layers */
.btn { background-color: navy; }
/* tailwind output — in @layer components, loses to legacy */
/* @layer components { .btn { ... } } */Importing Tailwind Alongside Legacy CSS
Import both Tailwind and legacy CSS in the correct order. In the main entry file, import Tailwind's output first (via PostCSS), then import legacy CSS. This way legacy styles are declared after the Tailwind output in the stylesheet, giving them precedence when specificity is equal. Never import legacy before Tailwind unless you intend Tailwind to override it.
/* main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Import legacy styles AFTER Tailwind so they can override when needed */
@import './legacy/reset.css';
@import './legacy/typography.css';
@import './legacy/components.css';
/* New component styles using @apply where needed */
@import './components.css';Avoiding Class Name Collisions
Tailwind's utility names rarely conflict with typical legacy class names, but collisions can occur. Common examples: a legacy .container class clashes with Tailwind's .container utility. Prefixing is the official solution — add a prefix in tailwind.config.js so all Tailwind classes become tw-flex, tw-bg-blue-500, etc., completely avoiding name overlap with legacy styles.
// tailwind.config.js
module.exports = {
prefix: 'tw-', // All Tailwind classes prefixed with 'tw-'
content: ['./src/**/*.{html,js}'],
theme: { extend: {} },
};
<!-- In HTML: use tw- prefix on all Tailwind classes -->
<div class="tw-flex tw-items-center tw-gap-4 tw-bg-blue-500">
<!-- Legacy classes work normally alongside -->
<div class="legacy-card header-title tw-text-white">
</div>Incremental Migration Strategy
Migrate component by component rather than attempting a full rewrite. Pick a low-risk component — perhaps a new button or badge — and style it entirely with Tailwind. Leave surrounding legacy code unchanged. Once the pattern proves stable, gradually replace legacy components one at a time. This approach limits the blast radius of any issues and keeps the project deployable throughout the migration.
<!-- BEFORE: legacy button -->
<button class="btn btn-primary btn-lg">Save</button>
<!-- AFTER: new Tailwind button (legacy .btn class removed) -->
<button class="rounded-lg bg-blue-600 px-6 py-3 font-semibold text-white
transition hover:bg-blue-700">Save</button>
<!-- DURING MIGRATION: both can coexist temporarily -->
<button class="btn btn-primary tw-ring-2 tw-ring-offset-2">Save</button>Disabling Tailwind's Preflight
Tailwind's Preflight (a CSS reset based on normalize.css) resets browser defaults aggressively. In a legacy project, these resets can break existing styles — removing heading sizes, clearing list styles, collapsing margins. You can disable Preflight in the config to preserve legacy browser defaults while still using all of Tailwind's utilities.
// tailwind.config.js
module.exports = {
corePlugins: {
preflight: false, // Disable the CSS reset
},
content: ['./src/**/*.{html,js}'],
theme: { extend: {} },
plugins: [],
};Selectively Scoping Tailwind
If only part of a legacy page should use Tailwind utilities, you can scope Tailwind's output to a specific CSS selector. Wrap the three @tailwind directives in a selector scope using PostCSS. All generated utilities will be nested under that selector, preventing them from leaking into the rest of the legacy page. This is the most surgical integration possible.
/* Using postcss-scopify or similar — scope Tailwind to .tw-scope */
.tw-scope {
@tailwind base;
@tailwind components;
@tailwind utilities;
}
<!-- In HTML: only elements inside .tw-scope use Tailwind -->
<div class="tw-scope">
<div class="flex items-center gap-4 bg-blue-500">
<!-- Tailwind works here -->
</div>
</div>
<!-- Outside .tw-scope: legacy CSS only -->
<div class="old-header"><!-- legacy --></div>Testing After Each Migration Step
After migrating each component, run a visual regression test to confirm nothing broke. Browser-based tools like Playwright's screenshot comparison or Chromatic catch unintended style changes automatically. At minimum, manually review the migrated component in all supported browsers and at key breakpoints before moving to the next migration target. Automated testing pays dividends in a long migration.
// Playwright visual regression example
import { test, expect } from '@playwright/test';
test('button renders correctly', async ({ page }) => {
await page.goto('/components/button');
await expect(page.locator('.btn-primary')).toHaveScreenshot('button.png');
});
// Run comparison:
npx playwright test --update-snapshots // First run: capture baseline
npx playwright test // Subsequent: compareRemoving Legacy CSS Safely
Once a component is fully migrated to Tailwind, delete the legacy CSS rules. Use browser DevTools' Coverage tab to identify CSS rules that receive zero hits on a given page — strong evidence they are unused. PurgeCSS can also report which selectors in your legacy file never matched any content, guiding the safe removal of dead CSS.
# Check CSS coverage in Chrome DevTools:
# 1. Open DevTools > Coverage tab (Ctrl+Shift+P → 'Show Coverage')
# 2. Start recording, interact with the page
# 3. Red bars indicate unused CSS rules — safe to delete if confirmed
# PurgeCSS analysis:
npx purgecss --css legacy.css --content 'src/**/*.html'
# Rules absent from the output were matched — keep
# Rules still in output were never matched — remove candidatesCommunicating Migration Progress
In team projects, track migration progress visibly. A simple spreadsheet or project board listing every component with status (Not started, In progress, Migrated, Legacy deleted) helps the team coordinate. Document any legacy classes still in use with a comment marking them for future deletion so they are not accidentally reintroduced or depended upon by new features.
/* MIGRATION STATUS: IN PROGRESS
Component: .header-nav
Tailwind replacement: planned in Sprint 12
Owner: @alice
Note: Used in _header.html and email-template.html
*/
.header-nav {
display: flex;
align-items: center;
gap: 1rem;
}Quick Check
Test your understanding of Tailwind CSS Mastery concepts from this lesson.
Lesson Recap
In this lesson you learned: managing specificity conflicts between Tailwind and legacy CSS using cascade layers, disabling Preflight and adding a prefix to avoid breaking or colliding with existing styles, and incrementally migrating components with visual regression testing and tracked progress. Next up we explore CSS Modules combined with Tailwind.
AI 튜터와 함께 HTML을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 30
- 레슨
- 120
자주 묻는 질문
“레거시 CSS와 함께 사용하기” 강의는 무료인가요?
네 — “레거시 CSS와 함께 사용하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“레거시 CSS와 함께 사용하기”에서 뭘 배우나요?
레거시 CSS 또는 다른 프레임워크가 있는 기존 프로젝트에 Tailwind를 통합하고, 우선순위 충돌을 관리하면서 점진적으로 마이그레이션합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“레거시 CSS와 함께 사용하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 파일 및 폴더 구성
- 레거시 CSS와 함께 사용하기
- CSS Modules와 Tailwind
- 모노레포 전반으로 Tailwind 확장하기