0
0
React Nativemobile~5 mins

Margin, padding, border in React Native

Choose your learning style9 modes available
Introduction

Margin, padding, and border help you control space and edges around your app elements. They make your app look neat and easy to use.

To add space outside a button so it doesn't touch other elements.
To add space inside a box so its content doesn't stick to the edges.
To draw a line around a picture or text to highlight it.
To separate sections in a list for better readability.
Syntax
React Native
const styles = StyleSheet.create({
  box: {
    margin: 10,       // space outside the box
    padding: 15,      // space inside the box
    borderWidth: 2,   // thickness of the border
    borderColor: 'blue' // color of the border
  }
});

Margin adds space outside the element.

Padding adds space inside the element, between content and border.

Border draws a line around the element.

Examples
Adds 20 units of space outside all sides of the element.
React Native
margin: 20
Adds 10 units of padding left and right, 5 units top and bottom.
React Native
paddingHorizontal: 10,
paddingVertical: 5
Draws a thin red border with rounded corners.
React Native
borderWidth: 1,
borderColor: 'red',
borderRadius: 5
Sample App

This app shows a white box centered on the screen. The box has space outside it (margin), space inside it around the text (padding), and a blue border around it.

React Native
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <Text style={styles.text}>Hello with margin, padding, and border!</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0'
  },
  box: {
    margin: 20,
    padding: 15,
    borderWidth: 3,
    borderColor: 'blue',
    backgroundColor: 'white'
  },
  text: {
    fontSize: 16
  }
});
OutputSuccess
Important Notes

Margin and padding can be set for all sides or individually (top, bottom, left, right).

Border color and width must be set together to see the border.

Use borderRadius to make rounded corners on borders.

Summary

Margin adds space outside an element.

Padding adds space inside an element.

Border draws a line around an element.