Skip to content
Advertisement

How to horizontally center the content of a div with css in React?

I have an HomeComponent as the following:

import "./Home.css";
import { Component } from "react";
import { Link } from "react-router-dom";
import axios from 'axios';

export default class Home extends Component {

    constructor(props) {
        super(props);
        this.state = {
            games: [],
        };
    }

    componentDidMount() {
        // the games are retrieved asynchronously with a call to an API and the state is changed
    }

    render() {
        return <div className="center">
            <Link className="btn btn-lg game-btn" to="/games/create"><i className="fa fa-play fa-fw"></i> Play a game!</Link>
            <div style={{marginTop: 20}}>
                {this.state.games.map((game) => {
                    return <div className="row">
                        <div className="col col-2">Play as { game.blackPlayerId? "white" : "black" }</div>
                        <div className="col col-2">{ game.timeLimit } minutes</div>
                        <div className="col col-2">{ game.isRated ? "Rated" : "Unrated" }</div>
                        <div className="col col-4"><Link className="btn btn-lg" to={ "/games/create/"+game.gameId }><i className="fa fa-play fa-fw"></i> Play a game!</Link></div>
                    </div>
                })}
            </div>
        </div>;
    }

}

In the Home.css file I have:

.center {
    text-align: center;
    justify-content: center;
    align-items: center;
}

.game-btn {
    background-color: #1e272e;
    color: white;
    width: 300px;
    height: 50px;
    font-size: larger !important;
    box-shadow: 0 4px 8px 0 rgb(0 0 0 / 30%), 0 6px 20px 0 rgb(0 0 0 / 25%);
    margin-top: 20px;
}

As you can see in the following image the Home.css style is applied correctly but the content is not properly centered (the Play button is center aligned but the row is not)

enter image description here

Advertisement

Answer

Check out this answer from a similar question for more suggestions. I’d recommend approach #2, using flexbox. If you want everything, including the button, to be centred in a single row, apply the following in .center:

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

To apply the style only to the items in .row:

.row {
  display: flex;
  align-items: center;
  justify-content: center;
}

Flex will be applied to the children of whatever element you add it to. If you want all of the .rows to be centred, apply flex to the parent div surrounding the map function.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement