Milan Cermak
Milan Cermak

Reputation: 8064

How to center a view inside another view in React Native?

I want to center one view inside another one in React Native.

This is my code:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'yellow',
  },
  outerCircle: {
    backgroundColor: 'blue',
    width: 100,
    height: 100,
    borderRadius: 100/2,
  },
  innerCircle: {
    backgroundColor: 'red',
    width: 80,
    height: 80,
    borderRadius: 80/2,
  }
});

export default class RecorderButton extends React.Component {

  _buttonPressAction() {
    Alert.alert("button pressed");
  }

  render() {
    return (
      <TouchableOpacity activeOpacity={0.4}
                        onPress={this._buttonPressAction}
                        style={styles.container}>
        <View style={styles.outerCircle}>
          <View style={styles.innerCircle} />
        </View>
      </TouchableOpacity>
    );
  }
}

And this is how it looks:

non-centered-cirlces

I want to have blue and red circles concentric. How do I achieve that?

Upvotes: 43

Views: 125637

Answers (3)

Mohd Sher Khan
Mohd Sher Khan

Reputation: 1087

make things center by these two followings

justifyContent: 'center', alignItems: 'center',

Upvotes: 11

Roberto Gimenez
Roberto Gimenez

Reputation: 304

You should center both, outer and inner circles, like this:

    const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'yellow',
  },
  outerCircle: {
    backgroundColor: 'blue',
    width: 100,
    height: 100,
    borderRadius: 100/2,
    justifyContent: 'center',
    alignItems: 'center',

  },
  innerCircle: {
    backgroundColor: 'red',
    width: 80,
    height: 80,
    borderRadius: 80/2,
    justifyContent: 'center',
    alignItems: 'center',

  }
});

Upvotes: 1

agenthunt
agenthunt

Reputation: 8678

You are already centering in the container. Follow the same for outerCircle as well.

  outerCircle: {
    backgroundColor: 'blue',
    width: 100,
    height: 100,
    borderRadius: 100/2,
    justifyContent: 'center',
    alignItems: 'center'
  },

Upvotes: 88

Related Questions