How To Make A Div Center In Screen In ReactJS

Introduction

This blog will guide you on how to make a div center on the screen. This is a very important interview question as well for a beginner-level react js developer. So let’s start.

Create a basic react js application

I have already explained how to create a basic react js application in one of my articles How To Get Started With React JS and other basic stuff for react js application in Understanding Folder Structure For React Project this article.

So please have a look at both articles if you are a beginner with react js.

Code

Replace your App.js code with below code,

import logo from './logo.svg';
import './App.css'; 

function App() {
  const centerDivStyle = {
      display: 'flex',  
      justifyContent:'center', 
      alignItems:'center', 
      height: '100vh'
    }; 
  return (
    <div>
      <div style={centerDivStyle}>
        <h1> Hello from React js </h1>
      </div>
    </div>
  );
}
export default App;

Explanation

First, we have to create a constant with name “centerDivStyle” and pass some attributes value.

  • Display: ‘flex’ => The flex sets how a flex item will grow or shrink to fit the space available.
  • justify-content => This property defines how the browser distributes space between and around content items along the main axis of a flex container.
  • alighItems => The align-items property specifies the default alignment for items inside the flexible container.

Use npm start command in VS code terminal to run the application and you will see below output window where you will find given div at center position. Even if you resize the screen still div will adjust at center of window.

How To Make A Div Center In Screen In ReactJS

Resize the window and see below output,

How To Make A Div Center In Screen In ReactJS

Summary

In this blog, we have learned how to make a div center on screen in react js application. It was a very small blog but very important for interview purposes.

Thank you!!