Last updated: Apr 6, 2024
Reading time·2 min
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.
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.
div
to cover the Full ScreenIf 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
.
#root { height: 100vh; }
And here is how you would import the App.css
file for the style to take
effect.
// 👇️ 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 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.