Skip to content
Advertisement

Align item to full parent’s width minus margin

How can I stretch my subview across 100% width of its parent, minus 20px margin on each side? In other words, I need it to fill the width of the parent, with 20px open on each side.

I know in React-Native I can use width: '80%' to make my subview’s width relative to that of its parent, but then it’s not always precisely 20px on the sides. I also know that I can use alignSelf: 'stretch', however that is not working for me – it has unexpected / unreliable results. I don’t want to use Dimensions, as the parent will not always be the device’s screen, so Dimensions.get('window').width is inadequate for this problem.

What other options do I have?

Advertisement

Answer

Use nested View. You can try here: https://snack.expo.io/@vasylnahuliak/stackoverflow-67989491

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

const App = () => {
  return (
    <View style={styles.container}>
      <View style={styles.child}>
        <Text style={styles.childText}>child</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 24,
    backgroundColor: 'tomato',
  },
  child: {
    height: 150,
    backgroundColor: 'navy',
  },
  childText: {
    color: 'white',
  },
});

export default App;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement