Set a Div's height to cover the full screen in React

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Set a Div's height to cover the full screen in React #

To set a Div's height to cover the full screen in React, set its height to 100vh, e.g. <div style={{height: '100vh'}}>...</div>. When the height of the element is set to 100vh, it covers 100% of the viewport's height.

App.js
const App = () => { return ( <div style={{height: '100vh'}}> <h2>hello world</h2> </div> ); }; export default App;

We used the vh unit to set a div's height to 100% of the viewport's height.

If you need to set the height of the root div in your React application, you can do that in your App.css file or in index.css.

App.css
#root { height: 100vh; }

And here is how you would import the App.css file for the style to take effect.

App.js
// 👇️ import your css file import './App.css'; const App = () => { return ( <div> <h2>hello world</h2> </div> ); }; export default App;

The example above assumes that the root div element in your public/index.html file has an id set to root.

You should make sure that you're targeting the root div correctly.

When importing global CSS files in React, it's a best practice to import the CSS file into your index.js file.

The index.js file is the entry point of your React application, so it's always going to be ran.

On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.