All we need is an easy explanation of the problem, so here it is.
I’m trying to make the first div in my App.js take 100% height:
App.css:
body,
html {
height: 100%;
}
App.js:
function App() {
return <div style={{ height: "100%", backgroundColor: "red" }}></div>;
}
The App component is rendered as default by index.js:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
The result is a blank white screen, not red. Why doesn’t the div rely on the parent (body) and then takes 100% of the height?
EDIT: I cannot use the 100vh trick, I would be happy to know what’s the reason for the direct children of the body that cannot inherit the body’s properties, specifically in React of course
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
You can use 100vh
(1vh
is relative to 1% of the height of the viewport):
function App() {
return (
<div style={{ minHeight: "100vh", background: "red" }}></div>
);
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
html,
body {
padding: 0;
margin: 0;
}
<script crossorigin src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Or you have to traverse the DOM tree and make sure all parent elements are 100%
height:
function App() {
return (
<div style={{ height: "100%", background: "red" }}></div>
);
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
html, body, #root {
height: 100%;
margin: 0;
padding: 0;
}
<script crossorigin src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Method 2
If you use
height:'100vh'
it works for me.
vh = view height, React seems to respond better to this unit than percent sometimes.
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0