Search code examples
javascriptcssreactjsreact-bootstrapinline-styles

How to Center React Component Horizontally and Vertically Using Inline Styles


I'm trying to center a basic user login in React JS using inline styles, but I can't seem to figure out how to do it. I'm using React Bootstrap and I have currently managed to partially center the form using flexbox, but it's still appearing at the top of the page. What do I need to do so that it appears right in the middle?

Please see the attached image for the current issue.

const LoginPage = () => {

    return (
        <Container >
            <Row
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginTop:'5px'
                }}
            >
                Enter API Key:
            </Row>
            <Row
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginTop:'5px'
                }}
            >
                <Form>
                    <Form.Control
                        id='apiKeyString'
                        name='apiKey'
                        size='sm'
                        style={{ width: '250px' }}
                        onChange={(e) => setApiKey(e.target.value)}
                    ></Form.Control>
                </Form>
            </Row>
            <Row
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginTop:'5px'
                }}
            >
                <Button type='submit' onClick={submitApiKey} size='sm'>
                    Submit
                </Button>
            </Row>
        </Container>
    );
};

enter image description here


Solution

  • To center vertically you'll have to set the Container inline style to the following:

    {
    height: '100vh',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    }
    

    This being done you can probably remove all the other styling.