Michal
Michal

Reputation: 469

How to use percentage padding top and bottom in React Native?

I am trying to achieve dynamic padding top and bottom. I am aware that paddingTop and paddingBottom with % will use the width of the container and I am fine with that.

Unfortunately when I do set the paddingTop to any value with %, it sets the paddingBottom to the same value. Basically paddingTop: '5%', paddingBottom: '0%' will give me equal 5% paddings on both sides.

If I set paddingBottom to any % value - it's just being added to the value that came form the top. So: paddingTop: '5%', paddingBottom: '10%' results in paddingBottom equal to 15%...

I checked the same solution in a web project and there it works as expected.

The snack presenting the problem: https://snack.expo.io/BJ9-2t8LB

The problem is on both Android and iOS.

How to solve it?

Upvotes: 5

Views: 15352

Answers (3)

Rai Akhtar Ali
Rai Akhtar Ali

Reputation: 1

const styles = StyleSheet.create({
  ayz:{
    marginTop:"15%",
    backgroundColor:'pink',
    alignItems:'center',
    justifyContent:'center',
  },
  asd:{
    color:'white',
    fontSize:50,
    fontWeight:'bold'
  }
});

Upvotes: 0

hong developer
hong developer

Reputation: 13906

Apply the value to the child container to be applied, not to the parent container.

I have modified the answer according to the conditions you want. You should send Bottom's territory to the parent's container. Because they interact with each other in their child's container, they must be independent.

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

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.wrapper}>
        <View style={styles.inner}>
          <View style={{ backgroundColor: 'yellow' }}>
            <Text>TOP</Text>
          </View>
        </View>
        <View style={{ backgroundColor: 'red', }}><Text>BOTTOM</Text></View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  wrapper: {
    flex:1,
    paddingLeft: 24,
    paddingRight: 24,
    backgroundColor: 'green',
    paddingBottom:"5%"
  },
  inner: {
    flex:1,
    justifyContent: 'space-between',
    backgroundColor: 'blue',
    marginTop:"10%"
  },
});

screen

Upvotes: 2

Zaytri
Zaytri

Reputation: 2574

That is strange behavior, you should bring it up as an issue to react-native.

In the meantime, a workaround would be applying marginTop and marginBottom to the inner View, instead of paddingTop and paddingBottom to the wrapper View.

Upvotes: 1

Related Questions