-1

I'm having trouble making my react app fill the whole screen while being able to size its children properly. Why is it that this works:

<div className="h-screen bg-blue-500">
    <div className="h-1/2 bg-red-500"></div>
</div>

and this doesnt:

<div className="min-h-screen bg-blue-500">
    <div className="h-1/2 bg-red-500"></div>
</div>

I've looked through the docs and other posts but nothing really touches on this specific problem. Also although h-screen makes it so that the children behave as expected, it doesn't fill the whole screen when there's a need to scroll. I'd appreciate any input, thank you.

  • Does this answer your question? [Percentage Height HTML 5/CSS](https://stackoverflow.com/questions/1622027/percentage-height-html-5-css) – Ahmed Shaqanbi Feb 01 '23 at 18:34

1 Answers1

0

This is simply how CSS works. The Tailwind class min-h-screen equates to min-height: 100vh; and the class h-1/2 equates to height: 50%. You cannot use a percentage as a height inside a container that doesn't have an explicit height (i.e., if its height is auto such that it is dependent upon the content inside of it).

The formal definition in the CSS specification says

[t]he percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.


One way to work around this is to add the grid class to the parent element. CSS grid containers have intrinsic height and width, so it is possible for your height: 50% child to use the intrinsic height of the grid to calculate its relative height.

This is fine if your container only has a single div such as in your example. However, the empty div will collapse as you add more content in one or more additional children containers.

If that's not the behavior you want, and you always want the one container to be 50% of the parent even if it overflows the min-height, then you can use grid-template-rows: 1fr 1fr (or in the case of Tailwind grid-rows-2 which translates to repeat(2, minmax(0, 1fr))) instead of height on the child:

<div className="min-h-screen bg-blue-500 grid grid-rows-2">
  <div className="bg-red-500"></div>
  <div>
    <p>Add as much or as little content here as you like.</p>
    <p>Both child divs will always have the same height of 50% relative to the parent</p>
  </div>
</div>
jme11
  • 17,134
  • 2
  • 38
  • 48