Search code examples
javascriptreactjsimagematerial-uiresponsive

How to make image responsive in Material-UI


I am trying to make a page responsive but, I am not able to make an image responsive as it is getting off the grid container in material UI. Is there a way I can make the image responsive? I am trying to add the image in Grid container, Still, it is showing the same.

import React from "react";
import "./styles.css";
import {
  Typography,
  Container,
  Grid,
  Button,
  CssBaseline
} from "@material-ui/core";
import useStyles from "./styles";
import Pic from "../../Assets/Images/manOnTable.svg";

const Home = props => {
  const classes = useStyles;

  return (
    <React.Fragment>
      <CssBaseline />

      <Grid container className={classes.root} style={{ height: "auto" }}>
        <Grid container sm={6} xs={12}>
          <Grid container style={{ padding: "20%" }}>
            <Grid item sm={12} xs={12}>
              <Typography variant="h3" color="textPrimary" gutterBottom>
                Hello, there.
              </Typography>
              <Typography variant="h5" paragraph>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua.
              </Typography>

              <Button
                variant="contained"
                color="primary"
                target="_blank"
                href="https://www.google.com/"
                disableElevation
              >
                Resume
              </Button>
            </Grid>
          </Grid>
        </Grid>

        <Grid container sm={6} xs={12}>
          <Grid container style={{ padding: "20%" }}>
            <Grid item sm={12} xs={12}>
              <img src={Pic} style={{ height: "50vh", width: "50vh" }} />
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </React.Fragment>
  );
};

export default Home;

enter image description here


Solution

  • In your image tag, you are setting the height and width to 50vh. Viewport units (vh or vw) will cause stuff to overflow out of containers if it sees fit. In your case, everything is working as intended, the image is taking up 50% of the viewport height (637/2 = 319px). It's going to overflow out of the grid container if it needs to in order to meet those dimensions.

    You should likely have the image itself have width: 100% height: 100%, or width: 100% height: auto and control the size of the image via the container (like you're already doing).

    Hope this helped, let me know if you have questions.