iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🃏

Why flex: 1 causes overlapping text and buttons in React Native and how to fix it

に公開

Introduction

When implementing a card-based UI in React Native, I encountered a layout issue where the text inside the card overlapped with the buttons.

The cause was the misuse of flex: 1. I was using it with the same intuition as web CSS Flexbox, but it leads to unexpected behavior within React Native's fixed-height containers.

Symptoms of the Issue

The design involved a stacked card UI where the front-most card displayed a question text, sample sentence, and a tap button arranged vertically.

Expected Layout:

┌──────────────────┐
│                  │
│       🌍        │
│  Question Text   │
│  Sample Text     │
│                  │
│  [Tap to Write]  │ ← Button
│                  │
└──────────────────┘

Actual Layout:

┌──────────────────┐
│                  │
│       🌍        │
│  Question Text   │
│  Sample Text Text│ ← Text and button overlap
│  [Tap to Write]  │ ← Button encroaches on text area
│                  │
│                  │
└──────────────────┘

Overlap became more pronounced in cards with more text, and it was particularly reproducible with a combination of a two-line question and a sample sentence.

The Cause: Behavior of flex: 1 in a Fixed-Height Container

Problematic Code

CardComponent.tsx
const styles = StyleSheet.create({
  cardOverlay: {
    flex: 1,
    backgroundColor: 'rgb(24, 48, 52)',
    padding: 16,
  },
  cardContent: {
    flex: 1,           // ← This is the cause
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonContainer: {
    marginTop: 12,
    alignItems: 'center',
  },
});

Why it overlaps

flex: 1 specifies that an element should occupy all remaining space. The problem here is how it behaves when the parent container has a fixed height (e.g., minHeight: 350).

Total Card (Height 350px)
├── cardOverlay (flex: 1 → 350px)
│   ├── cardContent (flex: 1 → tries to take all remaining space)
│   │   ├── Emoji (54px)
│   │   ├── Question text (~60px)
│   │   └── Sample text (~44px)
│   │   Total ~160px, but stretched to ~300px via flex: 1
│   └── buttonContainer (marginTop: 12)
│       └── Button (~50px)
│       Total ~62px
│
│   Total: 300 + 62 = 362px > 350px → Overflow & Overlap

Because cardContent with flex: 1 attempts to occupy all available space, the space for the subsequent buttonContainer is squeezed. It reserves more space than the actual content height (~160px), resulting in an overlap rather than a margin between it and the button.

Why this doesn't happen in SwiftUI

The SwiftUI version of the reference implementation used a VStack to achieve the same layout, and this issue does not occur.

VStack(spacing: 24) {
    // Content section
    VStack {
        Text(emoji).font(.system(size: 54))
        Text(questionText).font(.title2)
        Text(sampleAnswer).font(.body)
    }

    // Button
    Button("Tap to Write") { ... }
}
.frame(maxHeight: .infinity)

SwiftUI's VStack respects the natural size of its child views and uses spacing: 24 to ensure even margins. .frame(maxHeight: .infinity) means "it can expand up to the maximum available size" and does not stretch the child views.

On the other hand, React Native's flex: 1 is an action that actively seeks to fill all available space. This difference was the cause of the overlap.

Fix

Fix 1: Remove flex: 1 from cardContent

 const styles = StyleSheet.create({
   cardContent: {
-    flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
   },
 });

By removing flex: 1, cardContent will only occupy the natural size of its child elements (~160px). This ensures there is space for the button, resolving the overlap.

Fix 2: Add justifyContent: 'center' to the parent container

 const styles = StyleSheet.create({
   cardOverlay: {
     flex: 1,
+    justifyContent: 'center',
     backgroundColor: 'rgb(24, 48, 52)',
     padding: 16,
   },
 });

Now that cardContent has a natural height, the content will default to the top of the card. I added justifyContent: 'center' to the parent container to vertically center the entire content (text + button).

Fix 3: Adjust button margins

 const styles = StyleSheet.create({
   buttonContainer: {
-    marginTop: 12,
-    marginBottom: Platform.OS === 'ios' ? 32 : 24,
+    marginTop: 24,
     alignItems: 'center',
   },
 });
  • Increased marginTop from 12 to 24 to ensure sufficient space between the text and the button.
  • Removed marginBottom since the parent's padding is sufficient, which also eliminates the need for platform-specific branching.

Fix 4: Adjust minimum container height

 const styles = StyleSheet.create({
   cardStackContainer: {
-    minHeight: 350,
+    minHeight: 380,
   },
   stackContainer: {
-    minHeight: 300,
+    minHeight: 340,
   },
 });

Adjusted the minHeight of the containers so that the content fits comfortably at its natural height.

Layout structure after fix

Total Card (Height 380px)
├── cardOverlay (flex: 1, justifyContent: 'center')
│   ├── cardContent (natural height ~160px)
│   │   ├── Emoji (54px)
│   │   ├── Question text (~60px)
│   │   └── Sample text (~44px)
│   └── buttonContainer (marginTop: 24)
│       └── Button (~50px)
│
│   Total: 160 + 24 + 50 = 234px (fits comfortably within 380px)
│   Margins are distributed evenly vertically (justifyContent: 'center')

When to use (and avoid) flex: 1

Situation flex: 1 Natural Height
Container filling the whole screen ✅ -
ScrollView content - ✅
Multiple sections within fixed height Use with care ✅ (Recommended)
Content inside a card - ✅
Sharing space with siblings ✅ -

Decision Criteria

Cases where you should use flex: 1:

  • When you need to fill the entire screen (root container, immediately under SafeAreaView, etc.)
  • When you need to explicitly divide space with siblings (using ratios like flex: 1 and flex: 2)

Cases where you should avoid flex: 1:

  • When you want to display content at its natural size
  • Within a fixed-height parent container where content might overflow
  • When you only want to use justifyContent: 'center' for alignment

Summary

Key Takeaways

  1. flex: 1 means "occupy all remaining space" — It tries to reserve space regardless of the content's natural size.
  2. flex: 1 in fixed-height containers often causes overlaps — If the sum of child elements exceeds the container size, elements overlap.
  3. SwiftUI VStack and React Native flex: 1 are not the same — SwiftUI respects the natural size of children, while flex: 1 actively attempts to fill available space.
  4. Centering should be achieved via justifyContent: 'center' on the parent — Adding flex: 1 to children just to center them is overkill.

Flexbox Layout Checklist

  • Before using flex: 1, verify if you truly need to fill the space.
  • Check if you are using flex: 1 on children within a fixed-height container.
  • If centering is the goal, are you using justifyContent on the parent instead of flex: 1?
  • If you have spacing logic based on Platform.OS, is it just a workaround?
  • Verify by calculation that the sum of the natural sizes of content fits within the container.
GitHubで編集を提案

Discussion