preface

For front-end development that often moves around the Web side, we all know that the CSS position attribute, position: ‘Absolute’, is always set relative to the nearest element. Parent element of ‘absolute’. However this is not the case in React Native 😅 (once I foolishly thought it was the same 😿)

Now let me explore a little bit more about how position is defined and used in RN.

I deliberately read the definition of positioning in React-Native, which made me suddenly enlightened.

Absolute & Relative Layout

  • relative (default value) By default, an element is positioned relatively. This means an element is positioned according to the normal flow of the layout, and then offset relative to that position based on the values of top.right.bottom, and left. The offset does not affect the position of any sibling or parent elements.
  • absoluteWhen positioned absolutely, an element doesn’t take part in the normal layout flow. It is instead laid out independent of its siblings. The position is determined based on thetop.right.bottom, and left values.

In actual development, remember:

Absolute positioning

The absolute positioning of an element is relative to its parent element

<View style={styles.container}> <View style={styles.C1}> <View style={styles.p1}><Text>p1</Text></View> <View style={styles.p2}><Text>p2</Text></View> </View> <View style={styles.C2}><Text>C2</Text></View> <Text </View> p4 </View> p4 </View> p4 </View> p4 </View> p3: {backgroundColor: '#7951BD', padding: 10, position: 'absolute', bottom: -20, left: 20 },Copy the code

Notice the location of the p3 element in the figure below

Relative positioning

The relative position of an element is its original position relative to its non-absolute position sibling, which is top=0,left=0

Notice the position of the p4 element in the figure above

  • Complete test code:
const Test = () => { return( <View style={styles.container}> <View style={styles.C1}> <View style={styles.p1}><Text>p1</Text></View> <View style={styles.p2}><Text>p2</Text></View> </View> <View Style ={styles.C2}><Text>C2</Text></View> <Text style={styles. P3}>p3 relative parent </Text>< View >< font style={style. P4}>< / font ></ font ></ font style={container: {height: 300, width: 300, backgroundColor: '#eee', }, C1: { }, p1: { width: 40, height: 40, backgroundColor: '#5051BD', position: 'absolute', right: 0, bottom: 0, zIndex: 10 }, p2: { width: 40, height: 40, backgroundColor: '#1000DB', }, C2: { height: 80, width: '100%', backgroundColor: '#eea', left: 30, top: 20 }, p3: { backgroundColor: '#7951BD', padding: 10, position: 'absolute', bottom: -20, left: 20 }, p4: { backgroundColor: '#9951BD', // position: 'absolute', padding: 10, bottom: 0, left: 0 } })Copy the code

The knowledge point that article involves is oneself in daily development comprehension.

If there is any improper place, please correct 🤝🤝🤝! Let’s make progress together