Set a Div's height to cover the Full Screen in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# 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.

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;

set div height to cover full screen

The code for this article is available on GitHub

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

# Setting the height of the root div to cover the Full Screen

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;

setting height of root div to cover the full screen

The code for this article is available on GitHub

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 run.

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

I've also written a tutorial on how to get the height and width of an element.

If you need to check if an element is in the viewport, click on the following article.

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.