Broken CSS layout rescue on a developer laptop screen

How to Fix Broken Layouts After AI UI Generation (CSS Rescue Guide)

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.

Developer fixing broken CSS flexbox layout after AI-generated UI components collapsed on mobile viewport
AI-generated UI often looks perfect at one breakpoint — your job is making it survive real viewports and real content lengths.

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

  1. Why AI breaks layouts
  2. Diagnostic workflow
  3. Common flex and grid failures
  4. CSS rescue prompts
  5. Container queries and overflow
  6. Prevention for next generation
  7. 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:

  1. Identify the broken axis — horizontal overflow, vertical collapse, or z-index stacking?
  2. Shrink the viewport — DevTools responsive mode at 375px, 768px, 1280px
  3. Toggle flex/grid overlays — Chrome Layout panel or Firefox Grid inspector
  4. Find the overflow element — run document.querySelectorAll('*') filter for scrollWidth > clientWidth in console, or use “Scrollable overflow” in DevTools
  5. Check computed height chain — percentage heights fail when any ancestor lacks explicit height
  6. 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.”

SymptomLikely causeFirst check
Horizontal scrollbar on mobileFixed width, negative margin, 100vw including scrollbarSearch for w-[###px], -mx-, width: 100vw
Content clipped verticallyoverflow-hidden on parent with fixed heightInspect ancestors for h-screen, max-h-, overflow-hidden
Columns unequal heightMissing align-items stretch or grid align-itemsParent flex/grid align settings
Text overlappingAbsolute positioning without reserved spaceFind position absolute without relative parent padding
Sidebar pushes content off-screenflex-shrink: 0 on sidebar, no min-width: 0 on mainAdd 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.

PatternWhat AI generatesWhy it breaksFix pattern
Flex shrink trapflex-1 on text column without min-w-0Default min-width: auto prevents shrinking below content widthmin-w-0 on flex child; truncate or break-words on text
Grid blowoutgrid-cols-3 on all breakpointsThree columns at 320px crush contentgrid-cols-1 md:grid-cols-2 lg:grid-cols-3
Double full heighth-screen on layout AND mainNested 100vh exceeds viewport when headers existSingle min-h-dvh on root; flex column with flex-1 main
Gap vs margin soupMixing gap, space-x, and margin on siblingsInconsistent spacing; margin collapse surprisesPick gap OR margin strategy per container; document in prompt
Centering with absoluteabsolute top-1/2 left-1/2 -translate for layoutBreaks document flow; inaccessible focus orderFlex/grid centering on parent instead
Implicit grid tracksgrid without explicit rows; content variesRow heights jump when one card has more textgrid-auto-rows: 1fr or subgrid (where supported)
Stacking context warsRandom z-10, z-50 on siblingsDropdowns hide behind modalsCentralize z-index scale in tokens: dropdown 40, modal 50, toast 60
Image aspect ratioFixed height on img containerImages distort or overflowaspect-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.

CSS grid and flexbox inspector in browser DevTools highlighting overflow from AI-generated layout
DevTools layout overlays beat guessing — paste computed flex/grid values into your rescue prompt for surgical fixes.

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 token
  • Row — horizontal flex with gap, wrap optional
  • AppShell — header, sidebar, main with correct min-h-0 chain
  • PageContainer — max-width + horizontal padding responsive
  • CardGrid — 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.

Leave a Reply

Your email address will not be published. Required fields are marked *