Course contentsShow
← React Native
Lesson 292 of 1,5554. Flexbox and Native StylingFree lesson

Creating Card Layouts with Variable Content

Structure robust card containers that maintain alignment regardless of dynamic image or text inputs.

In this lesson, you will learn how to structure robust card containers that maintain perfect alignment even when your text lengths or image aspect ratios change dynamically.

The Challenge of Fluid Content

When building cards, the biggest UI enemy is "layout shift." If you have a card that displays a user's bio, a short string might make the card look empty, while a long string might push elements off-screen or break your alignment. To solve this, we move away from fixed heights and embrace Flexbox growth properties.

Designing Robust Containers

Instead of setting a fixed height on your card, allow the container to grow based on its children. Use a parent View with a defined padding and a borderRadius. Inside, use flexDirection: 'column' to stack your elements naturally.

If you have a primary image and text, utilize flexShrink or flexGrow to ensure the layout remains predictable. If an image has an unknown aspect ratio, wrapping it in a container with a fixed aspectRatio property prevents the card from "jumping" when the image loads.

const Card = ({ title, body }) => (
  <View style={styles.card}>
    {/* By not setting a height, the card stretches naturally */}
    <Text style={styles.title}>{title}</Text>
    <Text style={styles.body}>{body}</Text>
  </View>
);

const styles = StyleSheet.create({
  card: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 12,
    // Use margin to separate cards without affecting internal alignment
    marginHorizontal: 16, 
  },
  body: {
    marginTop: 8,
    // This allows text to wrap properly within the container's bounds
    flexShrink: 1, 
  }
});

Preventing Collapse

To maintain alignment across multiple cards, avoid hardcoding dimensions. If you need consistent visual boundaries, use minHeight instead of height. This ensures that if the content is small, the card maintains a minimum "clickability" size, but if the content is large, the card expands gracefully to accommodate the overflow without breaking the parent layout.

Key Takeaway: Never rely on fixed pixel heights for variable content; instead, use flex properties and minHeight to allow your containers to breathe while preserving your desired visual structure.