Thomas Lupo
Thomas Lupo

Reputation: 241

React-Native: Margin with percentage value

I'm trying to use percentage value for margin style attribute on my React Native project but it seems to reduce the height of one of my View component. If I replace percentage value by an absolute value, there is no more issue and it works fine. Did you try to use percentage value as margin in React Native ? Here is a little sample of code to reproduce this issue:

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

export default class App extends Component {
  render() {
    return (
      <View style={styles.scene}>
        <View style={styles.card}>
          <View style={styles.container}>
            <Text>Hello World</Text>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    scene: {
        backgroundColor: '#F9E8D5',
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
        flexDirection: 'column'
    },
    card: {
        backgroundColor: '#E6D5C3',
        flex: 0.2,
        flexDirection: 'column',
        marginTop: '20%' // Replace by 20
    },
    container: {
        backgroundColor: '#FFFFFF',
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center'
    }
});

Thank you very much !

Upvotes: 22

Views: 44465

Answers (2)

Joseph Garrone
Joseph Garrone

Reputation: 1762

This is a real bug but Facebook does not care.

https://github.com/facebook/react-native/issues/19164

Upvotes: 3

Jeeva
Jeeva

Reputation: 1590

A component's height and width determine its size on the screen.

The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.

Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.

Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1.

The following references will be use for styling

  1. https://facebook.github.io/react-native/docs/height-and-width.html

  2. https://medium.com/the-react-native-log/tips-for-styling-your-react-native-apps-3f61608655eb

  3. https://facebook.github.io/react-native/docs/layout-props.html#paddingtop

    Use Dimensions to calculate to get the height and width of the screen.

    var {height, width} = Dimensions.get('window');
    

    To specify percentage by getting the screen size and convert it into percentage.

    Sample example:

    const { height } = Dimensions.get('window');
    
    paddingTop: height * 0.1 // 10 percentage of the screen height
    

Upvotes: 26

Related Questions