James Ko
James Ko

Reputation: 34489

React Native: How do I set a button to be at the level of 70% of the height of its parent?

Suppose I want to position a button 30% of the way the down its parent element (i.e. the whole page) in React Native. How do I do this using Flexbox or some other method?

For example, adding justifyContent: 'center' to the parent element would work if I wanted the button to be 50% of the way down the page.

Here is my React layout / stylesheet:

<View style={styles.container}>
  <LinearGradient colors={['#e80ca3', '#e500ff', '#950ce8']} style={styles.linearGradient}>
    <View style={styles.scanContainer}>
      <View style={styles.scanButton} />
    </View>
  </LinearGradient>
</View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  linearGradient: {
    flex: 1,
    alignSelf: 'stretch',
    justifyContent: 'center', // What to put here to make `scanContainer` 30% instead of 50% of the way down?
  },
  scanContainer: {
    alignSelf: 'center',
  },
  scanButton: {
    width: 175,
    height: 175,
    borderRadius: 87.5,
    backgroundColor: 'green',
  },
});

Upvotes: 2

Views: 354

Answers (4)

CodeYute
CodeYute

Reputation: 74

Using flex:

<View style={[styles.scanContainer,{flex:1}]}>
   <View style={{flex:1}} />
   <View style={styles.scanButton} />
   <View style={{flex:2}} />
</View>

Using Dimension:

import {Dimensions} from 'react-native';
<View style={[styles.scanButton,{marginTop:Dimensions.get('window').height * 0.3}]} />

Upvotes: 0

Pritish Vaidya
Pritish Vaidya

Reputation: 22189

Here's the solution using flex properties

linearGradient: {
        flex: 1,
        alignSelf: 'stretch', //... Remove justifyContent: 'center',
    },
    scanContainer: {
        flex: 0.7,
        justifyContent: 'flex-end', // 30 % from the bottom
        alignSelf: 'center',
    },

Upvotes: 1

movietime
movietime

Reputation: 1

You can use absolute positioning for the button container.

scanContainer: {
  alignSelf: 'center',
  position: 'absolute',
  bottom: '30%',
  left: 0
}

Upvotes: 0

Roy Wang
Roy Wang

Reputation: 11260

You can add an empty View with flex 0.7 above the button:

  <View style={{ flex: 1 }}>
    <View style={{ flex: 0.7 }} />
    <Button title="button" />
  </View>

Upvotes: 0

Related Questions