Tips for optimizing your website design with Box layouts

I'm currently working on a web application using React along with Material UI. My objective is to create a layout that consists of two Boxes nested within a third Box. The bottom Box should adjust its height based on its content, while the top Box needs to occupy the remaining space within the third Box.

Here's the code snippet I have so far in my attempt to achieve this layout. However, it doesn't seem to be functioning correctly. Could someone provide assistance?

<Box
    component="main"
    sx={{
        height: '100vh',
        overflow: 'auto',
        justifyContent: "center",
        display: 'flex',
        flexWrap: 'wrap',
        alignContent: 'top',
        marginTop: '50px', 
        bgcolor: "green"
    }}
>
    
    <Box sx={{flexDirection: 'row'}}>
    {/* Content here */}
    </Box>
    <Box sx={{
            minWidth: '100%',
            bgcolor: "secondary.main",
            marginTop: "40px",
            marginBottom: "0px", 
            paddingBottom: "0px", paddingTop: "40px", 
            paddingLeft: "40px", paddingRight: "40px"
        }}>
        {/* Content here */}
    </Box>
</Box>

Answer №1

When you apply display: 'flex' to the main box, achieving this layout becomes simple. Just add alignContent: 'space-between', and that will align the two boxes to the vertical edges of the main container/Box.

Here is how your code should be structured:

<Box
      component="main"
      sx={{
        height: '100vh',
        overflow: 'auto',
        justifyContent: "center",
        display: 'flex',
        flexWrap: 'wrap',
        alignContent: 'top',
        marginTop: '50px',
        bgcolor: "green",
        alignContent: 'space-between'
      }}>
      <Box sx={{ flexDirection: 'row' }}>
        {/* Content here */}
      </Box>
      <Box sx={{
        minWidth: '100%',
        bgcolor: "secondary.main",
        marginTop: "40px 0 0 0",
        padding: '40px 40px 0 40px'
      }}>
        {/* Content here */}
      </Box>
    </Box>

Regarding your query about the top Box occupying all remaining space inside the third Box, keep in mind that the remaining space is already reserved for the top box as you add more content to it while the bottom box stays aligned at the bottom of the screen.

If you want more details, you can learn more about the align-content property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible that the use of excessive React.Fragment could impact performance negatively?

After a recent review of our company's code, I discovered that the performance is not up to par. One common pattern I noticed in the code is something like this: condition ? <SomeComponent /> : <></> I see that Fragments are being u ...

Utilizing properties to transfer a reference object to a nested component

Is it safe to do the following in React: function Parent() { const myRef = useRef([1, 2, 3]); console.log("parent: " + myRef.current); return <Child myList={myRef.current} />; } function Child({ myList }) { const [currInt, setCurrInt] = useS ...

How to eliminate the vertical scroll indicators in Material UI's TextField

I'm currently working on customizing the styling of a Material UI textfield and I need to remove the top-down arrows. Below is the code snippet I have so far: const theme = createMuiTheme({ MuiInput: { root: { "&::-webkit-outer-spin-bu ...

Finding the height of a dynamic div in ReactJS when no CSS height is set

I'm encountering an issue when trying to determine the height of a dynamically created div that doesn't have a defined CSS height property. I'm working with React JS and have attempted to use jQuery, pure JavaScript, and React tools to acces ...

Hiding the initial parent SVG element in the list will also hide all subsequent SVG elements within each section, excluding the container

I encountered a strange issue with my code in the Next framework. When using getServerSideProps, I made a request to my api folder, which resulted in a simple JSON response. Everything seemed to be working fine. The content was displayed perfectly without ...

Error encountered: No geographic indices found for executing a geoNear operation with Mongoose

Initially, I had divided the schemas but later nested them inside my overall document. Despite adding indexes and removing coordinates from location, there seems to be an issue with the nested points. Upon running get Indexes, it shows that there is an i ...

What is the proper method to change a property within a state object?

I am currently working with react 17.0.2 and next 12.0.0, utilizing the react-date-range library (https://www.npmjs.com/package/react-date-range) In my code, I have defined 3 states: const [calendarDates, setCalendarDates] = useState(null); const [wasClea ...

Resetting the column order in Mui Data Grid: A step-by-step guide

I need assistance with resetting column ordering in my React application: import * as React from 'react'; import Box from '@mui/material/Box'; import { DataGridPro } from '@mui/x-data-grid-pro'; import { useDemoData } from &ap ...

What is the best way to selectively add multiple classes to a single Material UI classes attribute based on certain conditions?

I am trying to use the Material UI Drawer and wish to add a class named "paperStyle" to the classes prop with the rule name "paper" and then, under certain conditions, apply an additional class called "specialPaperStyle" for specific users. However, I have ...

Ways to preserve codes on VS Code Mac?

Struggling with saving my ReactJS code in VS Code on a Mac. Whenever I try to save using command + s, the JSX formatting ends up in a mess. Check out the image here for reference: enter image description here Any solutions or tips on how to resolve this i ...

What steps should be taken to upgrade a ReactJS project to utilize Node.js version 18.12.0 and npm version 8.19.2

Having recently updated my Node.js version to 18.12.0, I encountered some errors when trying to run my React.js project with the command npm start. The errors displayed were: Compiled with problems:X ERROR in ./src/assets/images/arrow_vector.svg Module ...

The dialog box is not taking up the full width of the browser window

I'm facing an issue with a dialog box that only occupies a portion of the browser width, despite having a width set to 100%. The backdrop, however, extends across the entire width. //App.js import React from "react"; import ConfirmationDial ...

Unable to modify styles by using classes in material-ui

I am really struggling to grasp how to customize the styles for a one-time use of TextField The documentation is not connecting with me at all <FormControl> <InputLabel htmlFor="mobile-number-input" > Mobile Number </InputLab ...

Enabling the ability to merge rows or columns in a data table created with the Material Table component in React

I am currently utilizing the material-table plugin in ReactJS to generate a dataTable. However, I have not been able to identify a straightforward method or option within the plugin to implement rowspan or column span functionalities. Is there a workaround ...

Is there a way to ensure that the useEffect hook only runs after the useNavigate hook has been utilized? How can I prompt the initial render to occur only following the useNavigate

After using the useNavigate hook, how can I ensure that useEffect runs and triggers an initial render in my component? Within the App.js component, which serves as the homepage with the "/" path, the following code is implemented: const [contact ...

Sass issue: extending compound selectors is no longer supported

Encountered an error in my React app while running npm start. Using node version: v14.17.6 and npm version: 6.14.9 Error message: Failed to compile. Issue found in ./src/index.scss file with the following error: SassError: compound selectors may no long ...

The React table is failing to show the row data properly

Having trouble building a table, everything seems fine with the row data display but I'm encountering a strange issue. When I attempt to add a menu button, it ends up displaying the information from the last row for all the rows in the table. <T ...

Effortless bug tracking in Chrome developer tools

When I'm debugging, I want the code to be displayed in Chrome browser (or another browser like Edge) exactly as it was written. Even when using pretty print, the code still appears unreadable. For example, a block of code written in my IDE: {provideD ...

Filter products by pressing the "Enter" key while using the search input in

I have a list of products and I want to only display products that have a description or name containing the typed word when enter is clicked on the search input. Here is what I tried in my Search component: const Search = (props) => { return ( &l ...

The persistence of authentication state in Next.js Firebase is inconsistent

I can't figure out why Firebase auth isn't persisting. My project is quite basic at this point, with a simple sign-in function: await signInWithEmailAndPassword(auth, email, password); In my layout.tsx, I have the onAuthStateChange: const unsubs ...