Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

material-ui-next: Setting image size to fit a container

I've started out with Material-ui-next and have some problems with displaying images that they use the entire size of a container. E.g. I use:

const styles = theme => ({
  Card: {
    width: 300,
    margin: 'auto'
  },
  Media: {
    height: 550
  }
});

In render:

<Card className={classes.Card}>
   <CardMedia
        className={classes.Media}
        image={ImgPomodoR}
        title="a pomodoro tomatoe timer in material design"
   />
   <CardContent>
      <Typography gutterBottom variant="headline" component="h2">
        ...

The documentation says I have to specify a height for the image to get displayed. The 'media' example gives the image a height of 0, however, if I apply that my image is not getting displayed - mentioned example.

Right now, for me it's a trial and error of the Media-height, that it fits the Card container without being cropped. Is there no 'auto' way of doing this?

Any help is highly appreciated, cheers mates,

Tobias

Edit: I should mention that height: "100%" // maxHeight: "100%" does also not work for me.

like image 284
Caruso33 Avatar asked Jan 29 '23 03:01

Caruso33


1 Answers

I was having the same issue. Setting both width and height to '100%' worked for me.

const styles = theme => ({
  Card: {
    width: 300,
    margin: 'auto'
  },
  Media: {
    height: '100%',
    width: '100%'
  }
});

However, if your images have different heights, this will cause cards to be different heights and most of the time that is not what you want. For that, you can specify a height and keep the width at '100%'.

const styles = theme => ({
  Card: {
    width: 300,
    margin: 'auto'
  },
  Media: {
    height: 550,
    width: '100%'
  }
});

This will stretch the images to fit the container. For my case, I wanted part of the image to be shown without stretching the images. To achieve this, simply set the objectFit property to cover. This worked nicely for me.

const styles = theme => ({
  Card: {
    width: 300,
    margin: 'auto'
  },
  Media: {
    height: 550,
    width: '100%',
    objectFit: 'cover'
  }
});

Hope this helps someone,

like image 56
Ege Aydın Avatar answered Jan 31 '23 09:01

Ege Aydın