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?
CodePudding user response:
If you use
height:'100vh'
it works for me. vh = view height, React seems to respond better to this unit than percent sometimes.
CodePudding user response:
You can use 100vh
(Relative to 1% of the height of the viewport):
// Example stateless functional component
function App() {
return (
<div style={{ minHeight: "100vh", background: "red" }}></div>
);
}
// Render it
ReactDOM.render(
<App />,
document.getElementById("root")
);
html,
body {
padding: 0;
margin: 0;
}
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
Or you have to traverse the DOM tree and make sure all parent elements are 100%
height:
// Example stateless functional component
function App() {
return (
<div style={{ height: "100%", background: "red" }}></div>
);
}
// Render it
ReactDOM.render(
<App />,
document.getElementById("root")
);
html, body, #root {
height: 100%;
margin: 0;
padding: 0;
}
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>