App.jsx App.jsx App.jsx

Box component goes over Grid height

58 Views Asked by At

Home.jsx

        <Box component="fieldset" sx={{borderRadius:2, height:"100%"}}>

App.jsx

  <Grid container>
      <Grid item xs={4} >  
        <Root/>
      </Grid> 

       <Grid item xs={8} > 
       <BrowserRouter>
        <Routes>
          <Route path='/' element={<Home/>}/>
        </Routes>
       </BrowserRouter>
      </Grid> 
   
   
  </Grid>

I've put "height:100%" in the Box in Home.jsx because otherwise box is really small cuz there is not much content. I thought this will stretch the height of a box to the height of the Grid, but it goes a little bit over. I can of course play with Home.jsx Box height but obviously I don't wanna do that, especially cuz there will be more Boxes from different pages.How can I make it so it just fills out the Grid height? Thanks

EDIT: enter image description here

EDIT 2: Here's the Grid view through Dev tools enter image description here

2

There are 2 best solutions below

2
Jonatan Kruszewski On

First things first

There are many ways to solve this issue. The first one would be to create properly aligned elements, which without seeing the completeness of the code it is hard to reproduce.

The workaround

An improper but effective alternative could be to measure both element's heights and assign the highest value to both of them.

This post explains how.

Basically, you attach a ref to each element, and using useLayoutEffect you measure them and update the ref.current.clientHeight.

0
Steve G On

Add the CSS property box-sizing with a value of border-box to your Box (fieldset) component.

border-box tells the browser to account for any border and padding in the values you specify for an element's width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width.

For example:

<Box
  component="fieldset"
  sx={{ borderRadius: 2, height: "100%", boxSizing: "border-box" }}
>
 ...
</Box>

Which produces:

example with box-sizing

Working CodeSandbox: https://codesandbox.io/s/box-sizing-njgzc4?file=/demo.tsx