0
0
React Nativemobile~5 mins

Position (relative, absolute) in React Native

Choose your learning style9 modes available
Introduction

Positioning helps you place elements exactly where you want on the screen. It makes your app look neat and organized.

To move a button to the bottom right corner of the screen.
To place a label on top of an image.
To create a custom layout where items overlap.
To fix a header at the top while scrolling content below.
Syntax
React Native
style={{ position: 'relative' | 'absolute', top?: number, left?: number, right?: number, bottom?: number }}

relative means the element moves relative to its normal place.

absolute means the element moves relative to its closest positioned parent or the screen.

Examples
This moves the element 10 units down and 20 units right from where it normally is.
React Native
style={{ position: 'relative', top: 10, left: 20 }}
This places the element at the top-right corner of its parent container.
React Native
style={{ position: 'absolute', top: 0, right: 0 }}
This places the element 10 units above the bottom and 10 units from the left of its parent.
React Native
style={{ position: 'absolute', bottom: 10, left: 10 }}
Sample App

This example shows two boxes inside a container. The blue box uses relative positioning and moves 20 units down and right from its normal place. The red box uses absolute positioning and is placed 50 units from the top and left of the container, overlapping the blue box.

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

export default function PositionExample() {
  return (
    <View style={styles.container}>
      <View style={styles.boxRelative}>
        <Text>Relative</Text>
      </View>
      <View style={styles.boxAbsolute}>
        <Text>Absolute</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#eee',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative'
  },
  boxRelative: {
    width: 100,
    height: 100,
    backgroundColor: 'skyblue',
    position: 'relative',
    top: 20,
    left: 20,
    justifyContent: 'center',
    alignItems: 'center'
  },
  boxAbsolute: {
    width: 100,
    height: 100,
    backgroundColor: 'salmon',
    position: 'absolute',
    top: 50,
    left: 50,
    justifyContent: 'center',
    alignItems: 'center'
  }
});
OutputSuccess
Important Notes

Absolute positioned elements ignore the normal layout flow and can overlap other elements.

Relative positioning moves the element but keeps its original space reserved.

Always set the parent container's position if you want absolute children to be positioned relative to it.

Summary

Positioning controls where elements appear on the screen.

Relative moves elements from their normal spot.

Absolute places elements exactly inside their parent or screen.