sir-haver
sir-haver

Reputation: 3602

React cannot set div to take 100% of screen height

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

Upvotes: 0

Views: 3523

Answers (2)

Matt Carlotta
Matt Carlotta

Reputation: 19782

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/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/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/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 1

arfi720
arfi720

Reputation: 771

If you use

height:'100vh'

it works for me. vh = view height, React seems to respond better to this unit than percent sometimes.

Upvotes: 0

Related Questions