Fix broken layouts after AI UI generation is the skill every vibe coder learns on day three — right after the agent ships a gorgeous hero section that collapses on mobile, overlaps the nav, and ignores your design tokens entirely. AI excels at component syntax and copy-paste patterns; it routinely fails at box model discipline, flex shrink behavior, grid track math, and cascade conflicts between generated utility classes and your global stylesheet. This CSS rescue guide gives you diagnostic prompts, failure-pattern tables, and a repeatable workflow to recover layouts without rewriting the whole app. Updated November 2026.

Start from the vibe coding roadmap and AI prompts for UI generation so you generate fewer layout bugs upstream. When components ship broken, pair this guide with debugging prompts and accessible UI prompts — layout fixes often expose focus order and contrast issues too. For design-token alignment, see Figma variables to code handoff.
Table of contents
- Why AI breaks layouts
- Diagnostic workflow
- Common flex and grid failures
- CSS rescue prompts
- Container queries and overflow
- Prevention for next generation
- FAQ
Why AI breaks layouts after UI generation
Coding agents optimize for “looks correct in the preview iframe” — usually a desktop width, short placeholder text, and no sibling components competing for space. They stack flex, grid, absolute positioning, and negative margins until the screenshot passes. They rarely test:
- Long usernames, German compound words, or dynamic chart labels
- 320px viewports with browser chrome and safe areas
- Nested scroll regions inside modals and drawers
- Print styles, reduced motion, or high-contrast mode
- Third-party widgets (ads, embeds) with unpredictable dimensions
They also mix layout paradigms in one component tree: a parent is display: grid while children use flex-1 Tailwind classes expecting a flex parent. Or they apply h-screen on nested containers, creating double scrollbars. The fix is rarely “one magic class” — it is systematic inspection, constraint restatement, and prompts that force the agent to explain box model decisions before editing.
Review every layout PR with how to review AI-generated code. Treat layout regressions as architecture smells: if three prompts fixed the same sidebar, your layout primitives need a shared AppShell component documented in system prompt templates.
Diagnostic workflow before you prompt
Do not ask the AI to “fix the layout” without evidence. Run this five-minute checklist:
- Identify the broken axis — horizontal overflow, vertical collapse, or z-index stacking?
- Shrink the viewport — DevTools responsive mode at 375px, 768px, 1280px
- Toggle flex/grid overlays — Chrome Layout panel or Firefox Grid inspector
- Find the overflow element — run
document.querySelectorAll('*')filter forscrollWidth > clientWidthin console, or use “Scrollable overflow” in DevTools - Check computed height chain — percentage heights fail when any ancestor lacks explicit height
- Screenshot + annotate — paste into the agent with arrows pointing at misaligned edges
Export the offending component’s computed styles for the broken breakpoint. Agents fix faster when you paste “parent: display flex, flex-direction row, align-items stretch; child 2: min-width auto (default), content 400px” than when you say “cards look weird.”
| Symptom | Likely cause | First check |
|---|---|---|
| Horizontal scrollbar on mobile | Fixed width, negative margin, 100vw including scrollbar | Search for w-[###px], -mx-, width: 100vw |
| Content clipped vertically | overflow-hidden on parent with fixed height | Inspect ancestors for h-screen, max-h-, overflow-hidden |
| Columns unequal height | Missing align-items stretch or grid align-items | Parent flex/grid align settings |
| Text overlapping | Absolute positioning without reserved space | Find position absolute without relative parent padding |
| Sidebar pushes content off-screen | flex-shrink: 0 on sidebar, no min-width: 0 on main | Add min-w-0 to flex child that should shrink |
Common flex and grid failures in AI-generated CSS
These patterns appear in roughly 80% of layout rescue sessions across Cursor, Lovable exports, and v0 output. Memorize them and you will prompt faster.
| Pattern | What AI generates | Why it breaks | Fix pattern |
|---|---|---|---|
| Flex shrink trap | flex-1 on text column without min-w-0 | Default min-width: auto prevents shrinking below content width | min-w-0 on flex child; truncate or break-words on text |
| Grid blowout | grid-cols-3 on all breakpoints | Three columns at 320px crush content | grid-cols-1 md:grid-cols-2 lg:grid-cols-3 |
| Double full height | h-screen on layout AND main | Nested 100vh exceeds viewport when headers exist | Single min-h-dvh on root; flex column with flex-1 main |
| Gap vs margin soup | Mixing gap, space-x, and margin on siblings | Inconsistent spacing; margin collapse surprises | Pick gap OR margin strategy per container; document in prompt |
| Centering with absolute | absolute top-1/2 left-1/2 -translate for layout | Breaks document flow; inaccessible focus order | Flex/grid centering on parent instead |
| Implicit grid tracks | grid without explicit rows; content varies | Row heights jump when one card has more text | grid-auto-rows: 1fr or subgrid (where supported) |
| Stacking context wars | Random z-10, z-50 on siblings | Dropdowns hide behind modals | Centralize z-index scale in tokens: dropdown 40, modal 50, toast 60 |
| Image aspect ratio | Fixed height on img container | Images distort or overflow | aspect-ratio + object-cover; width 100% |
Flex rescue in plain language
Flexbox distributes free space along the main axis. AI forgets that flex items will not shrink below their content’s minimum size unless you set min-width: 0 (horizontal flex) or min-height: 0 (vertical flex). This single rule fixes more “mysterious mobile overflow” bugs than any other. For side-by-side layouts, prompt explicitly: “Parent: display flex, flex-direction row, gap token-md. Sidebar: width 280px, flex-shrink 0. Main: flex 1, min-width 0.”
Grid rescue in plain language
CSS Grid assigns children to tracks. AI loves grid-cols-12 with col-span-8 without responsive spans — fine on desktop, catastrophic on phone. Prefer named grid areas for page shells: grid-template-areas: "header" "sidebar" "main" with media query flip at lg breakpoint. See Figma Make to production for why design-tool grids do not always map 1:1 to CSS grid without handoff notes.

Copy-paste CSS rescue prompts
Run one prompt per commit. Include file paths, breakpoint, and screenshot description.
1. Layout audit only — no edits: List all elements causing horizontal overflow below 768px in components/Dashboard.tsx. For each, cite className, computed width, and parent display mode. Propose minimal fix ranked by invasiveness. 2. Fix flex shrink: In components/SidebarLayout.tsx, main content overflows horizontally on mobile. Parent is flex row. Add min-w-0 to main column, ensure sidebar is flex-shrink-0 w-64 hidden below md. Do not change colors or copy. 3. Replace h-screen stack: App shell uses nested h-screen causing double scroll. Refactor to min-h-dvh flex flex-col; header flex-shrink-0; main flex-1 overflow-y-auto. Files: app/layout.tsx, components/Header.tsx. 4. Responsive grid: Card grid in components/ProductGrid.tsx is grid-cols-4 at all breakpoints. Change to grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6. Cards equal height via grid auto-rows 1fr and flex flex-col inside card. 5. Z-index scale: Dropdown menus render behind modal overlay. Audit all z-index in project; replace ad-hoc values with tokens z-dropdown 40, z-modal 50, z-toast 60 from tailwind.config. List files changed. 6. Image overflow: Product images break card bounds. Container aspect-square overflow-hidden rounded-lg; img w-full h-full object-cover. Fix components/ProductCard.tsx only. 7. Absolute to flow: Hero CTA uses absolute positioning overlapping headline on small screens. Refactor to flex flex-col gap-4; remove absolute from children. Preserve visual hierarchy with spacing tokens only. 8. Modal scroll trap: Modal body does not scroll; footer clipped. Modal structure: flex flex-col max-h-[90dvh]; header/footer flex-shrink-0; body flex-1 overflow-y-auto min-h-0. 9. Table responsive: Data table overflows viewport. Wrap in overflow-x-auto; set min-w-0 on wrapper; sticky first column optional. Do not shrink font below 14px. 10. Token alignment: Replace hardcoded px spacing in components/ with spacing tokens from tailwind theme (4, 6, 8, 12, 16). List replacements; no layout structure changes. 11. Container query cards: Card grid should reflow based on container width not viewport. Add @container to parent; use @md:grid-cols-2 @lg:grid-cols-3 container queries. Match pattern in design system doc. 12. Safe area: Fixed bottom nav ignores iOS safe-area-inset-bottom. Add pb-safe or env(safe-area-inset-bottom) padding to components/MobileNav.tsx. 13. Print layout: Dashboard sidebar prints on every page. Add print:hidden to sidebar; main print:w-full. Only @media print rules in globals.css. 14. RTL sanity: Flex row layouts break in RTL. Use logical properties margin-inline-start instead of ml-; gap instead of space-x. Audit components/Nav.tsx. 15. Regression test prompt: After layout fix, list viewports to manually verify: 320, 375, 768, 1024, 1440. For each, note component and expected behavior. Add Playwright visual test optional for Dashboard at 375px.
Chain layout fixes with prompt chains for multi-file refactors when the bug spans layout shell + page + card components. Never combine prompt 4 and prompt 8 in one diff — you will not know which change broke the modal.
Container queries, overflow, and stacking
Viewport media queries are insufficient when AI drops the same card component into a narrow sidebar and a full-width main column. Container queries (@container) let components respond to parent width — closer to how Figma auto-layout frames behave. Prompt 11 above is the pattern; browser support is production-ready in 2026 for vibe-coded Next.js and Vite apps.
Overflow discipline: AI adds overflow-hidden to clip rounded corners, then forgets it blocks dropdowns. Rule: overflow-hidden only on leaf visual wrappers (image cards), never on ancestors of popovers. Use overflow-visible on flex parents of menus unless you intentionally scroll.
Stacking contexts: Each transform, filter, opacity < 1, and position: fixed ancestor creates a new context. AI animates cards with transform and wonders why tooltips clip. Fix: portal tooltips to document body (Radix, Headless UI) or move transform to inner wrapper.
Prevention: layout constraints in generation prompts
Rescue is expensive. Add this block to your UI generation system prompt (see system prompt templates):
- App shell: flex column, min-h-dvh, single scroll region in main
- No h-screen on nested elements
- All flex children that should shrink: min-w-0 or min-h-0
- Responsive grids: mobile-first col counts
- No absolute positioning for document layout — only for decorative overlays
- Use gap not space-x/y for sibling spacing
- Images: aspect-ratio + object-cover
- Z-index from centralized scale only
When generating from Figma, export layout annotations via variables handoff and motion handoff tools — but layout constraints belong in the prompt, not only in the PNG.
Layout component library
Extract after your second rescue session:
Stack— vertical flex with gap tokenRow— horizontal flex with gap, wrap optionalAppShell— header, sidebar, main with correct min-h-0 chainPageContainer— max-width + horizontal padding responsiveCardGrid— responsive columns with container query variant
Prompt all new UI to compose from these primitives. Agents copy existing patterns more reliably than inventing layout from scratch each time.
When to stop vibe coding the layout
If you have spent more than two hours on the same overflow bug across three prompts, escalate: hire a frontend developer for a half-day layout audit, or rebuild the shell manually. Read vibe coding vs vibe engineering — engineering means knowing when AI output is cheaper to replace than repair.
FAQ
Should I switch from Tailwind to CSS Modules for layout stability?
Not necessarily. Tailwind is fine when you enforce layout primitives and tokens. The bug is unconstrained generation, not utility CSS. CSS Modules do not stop AI from writing bad flex parents.
Why does my Lovable export break after I add one component in Cursor?
Export often lacks shared layout shell conventions. Import into Cursor with a layout audit prompt (prompt 1) before adding features. Compare tools in Cursor vs Lovable 2026.
Can I ask AI to “make it responsive” in one shot?
You can, but results are inconsistent. Better: specify breakpoints, column counts, and which element scrolls. One-shot responsive prompts often add display:none on mobile instead of proper reflow.
Do component libraries fix AI layout issues?
shadcn/ui and Radix improve primitives (dialogs, dropdowns) but AI still miscomposes them in custom grids. Libraries reduce z-index and focus bugs; they do not replace layout shell discipline.
Fix broken layouts after AI UI generation by diagnosing overflow and flex/grid failures before prompting, using surgical rescue prompts one at a time, and encoding layout rules in your system prompt so the next generation starts cleaner. Pair this guide with UI generation prompts, debugging prompts, and the vibe coding roadmap — layout rescue is a core skill, not a one-time fire drill.
