CodeBlanks Logo Icon CodeBlanks

Margin and padding

Learn spacing with margin and padding.

margin and padding

Spacing comes from two properties. padding is the space between a component's inner edge and its content; margin is the space between the outer edge and its neighbors. Both take a pixel number.

Concrete example: when you put <Text>Hi</Text> inside a View, padding: 12 keeps the text 12 pixels away from the box edge. margin: 12 keeps the box itself 12 pixels away from its neighbors. Use padding for inner space, margin for outer space.

Practice Write a card with spacing

Fill the empty StyleSheet.create block. Define a style named card with padding: 16 and margin: 8. The component returns <View style={styles.card}><Text>Card</Text></View>.

Starter code

App.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function Card() {
  return (
    <View>
      <Text>Card</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  // Add the card style here
});

Sample solution

App.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function Card() {
  return (
    <View style={styles.card}>
      <Text>Card</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  card: { padding: 16, margin: 8 }
});

Directional spacing

A single padding applies to all four edges. To space only one edge use directional suffixes: paddingTop, paddingBottom, paddingLeft, paddingRight. The same applies to margin: marginTop, marginBottom and so on.

There is no shorthand for horizontal and vertical; paddingHorizontal sets left and right together, paddingVertical sets top and bottom together. These do not exist in CSS and are specific to React Native. First set every edge with padding: 12, then use a directional suffix when one edge needs to differ.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which property gives inner space?

App.js
<View style={{ ??? : 12 }}>
  <Text>Hi</Text>
</View>
  • margin
  • outer
  • borderWidth
  • padding Correct answer

Explanation: padding gives inner space.

2 Write the top padding property

Question
styles = StyleSheet.create({
  card: {____: 16, padding: 8 }
});
Answer
styles = StyleSheet.create({
  card: {paddingTop: 16, padding: 8 }
});

Explanation: paddingTop sets the top edge space.

3 Match each property to its direction

Term Meaning
paddingTop Top inner space
marginBottom Bottom outer space
paddingHorizontal Left and right inner space
margin All outer edges

All lessons in Beginner