What is the best way to expand my container element and add margins to the top and bottom?

Currently, I am utilizing the Material-UI library in combination with ReactJS, but facing some challenges pertaining to flexbox.

The objective is to position my Item Container at the center of my div, extending it to occupy the entire available height while also defining margin values for top and bottom.

I attempted using alignItems="stretch" without success as per the original code. Alternatively, setting the heights of both Grid Item and Paper components to 100% seems like a less refined approach to ensuring the element fills all vertical space (second code version).

In addition, when applying a height of 100% to both Grid Item and Paper, along with assigning margin values to each element for top and bottom, the bottom margin gets disregarded by the Paper component entirely. Furthermore, there are occurrences where the width and height surpass the screen size (refer to second image below), causing concern on why this happens.

Original version:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    height: "100%"
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
}));

export default function CenteredGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container style={{height: "100%", backgroundColor:"green"}} justify= "center" alignItems="stretch"spacing={3}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>xs=12</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

Second version:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    height: "100%"
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: 'center',
    height: "100%",
    color: theme.palette.text.secondary,
  },
}));

export default function CenteredGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container style={{height: "100%", backgroundColor:"green"}} justify= "center" alignItems="stretch" spacing={3}>
        <Grid item xs={12} style={{backgroundColor: "red", marginTop:10, marginBottom:10}}>
          <Paper className={classes.paper}>xs=12</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

Within my index.css file, every component has been set to height="100%".

body {
  height: 100%;
  width: 100%;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;

  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

html {
  height: 100%;
  width: 100%;
}

div#root {
  height: 100%; /* remove this line to see div.app is no more 100% height */
  width: 100%;
  background-color: indigo;
}

div.app {
  height: 100%;
  width: 100%;
  background-color: cornsilk;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}

The desired outcome involves a Grid Item housing a Paper element that is centrally positioned within the Grid container, stretching its height to encompass all vertical space while maintaining specified top and bottom margins.

Results obtained from My Original Code: https://i.stack.imgur.com/uUX65.png

Results achieved from My Second Version Code: https://i.stack.imgur.com/iac9X.png

Inquiry:

Having previously worked with React Native, I find the implementation of flexbox on mobile devices to be more intuitive. Can anyone recommend valuable resources or tutorials that offer comprehensive guidance on managing UI in ReactJS, complete with practical code samples?

Answer №1

Take a look at this updated codesandbox code where I have made the necessary fixes. To remove the red border, simply add padding:0 to the item-container.

Furthermore, I recommend avoiding mixing styles. You currently have inline styling alongside styles created with makeStyle. It's best to stick to one method for easier management and updates in the future.

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

What is the best way to reset the selected label in a React Material AutoComplete component when the state is

I currently have a state declared as: const [searchEntryNo, setSearchEntryNo] = useState(''); In addition, there is a function set up to clear the state when needed. const handleClear = () => { setSearchEntryNo(''); }; Ne ...

The accentColor is not recognized by the TextStyle function, leading to an incorrect color being displayed

While working in MaterialApp's theme, I am encountering an issue with the color of headline6. Despite setting it to use accentColor, the displayed text appears in a different color than expected. theme: ThemeData( accentColor: const Color(0xffAEB8C ...

Utilizing hooks to pass properties from a parent component to a child component

As someone who is new to react, I am currently facing an issue with passing props from a parent function to a child. It seems that the parameters "square_state" and "setSquare_state" are not being recognized in the useSquare or handle_square_click functi ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Exploring the implementation of --history-api-fallback in webpack

let path = require('path') module.exports = { entry:path.resolve('public/src/index.js'), output: { path:__dirname + "/public", filename: "bundle.js" }, module: { loaders: [{ exclude: / ...

What is the trick to shortening paragraphs with dots...?

There is a p tag, <p> most iconic character in cinema</p> I need to truncate the text after 8 characters, and display dots afterwards. For example: most ic... Is there a way to achieve this using CSS? Any help with AngularJS would also be ...

Legend alignment issue in Firefox disrupting Flexbox functionality

My fieldset has a legend containing text and a button. I am attempting to use flexbox to right-align the button within the legend. This setup works correctly in Chrome, but encounters issues in Firefox. I have managed to replicate the problem with a simpl ...

Failure to Connect HTML with Stylesheet

Feeling a bit lost here. I've been attempting to connect my homepage to my stylesheet, but no matter how often I refresh the page, it just won't recognize the link. I'm diligently following the instructions from the guide I have, copying and ...

How to creatively position custom arrows in a React JS Nuka Carousel

Seeking assistance on properly positioning custom arrows within the Nuka Carousel component. After combining the decorators, I found that both of my arrows are appearing side by side. How can I address this issue? My goal is to have one arrow positioned in ...

Did Material version 5 eliminate the createBreakpoints method?

I am attempting to utilize the createBreakpoints method in my code: import createBreakpoints from '@material-ui/core/styles/createBreakpoints' import { createTheme } from '@material-ui/core' const breakpoints = createBreakpoints({}) c ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

Capturing the action phase in Liferay to change the cursor to 'waiting' mode

I'm currently working on a large Liferay project and have encountered a specific issue: Whenever something in the system is loading or processing, I need to change the cursor to a waiting GIF. While this is simple when using Ajax, there are many inst ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

Overriding makeStyles CSS in Material UI Styling

When creating classes using makeStyles and useClasses, I've noticed that MUI CSS tends to take precedence over my custom styles unless I use the '!important' rule. Is there a way to override MUI styles without having to rely on '!import ...

Safari is not properly handling element IDs when used in conjunction with React

I am currently in the process of building a straightforward single-page website utilizing React. At the top of the page, there is a navigation bar that contains links to various sections of the site: <li><a href="/#about">About u ...

CSS media query to center the logo on mobile screens

As someone new to CSS and media queries, I'm reaching out for help from the experts. My challenge involves positioning a mat-toolbar with a menu button and app logo. The HTML code in question is as follows: <div class="toolbar"> <mat-too ...

What is the best way to trigger the OnChange function in React when using Formik and Ant Design components together?

Is there a way to call a custom function on a Formik field when using the onChange event? I've tried calling it but it's not working as expected. Below is my custom function within a React Component: onStudentScore = (value, form) => { ale ...