Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MUI Card text overlay

I'm using the MUI Card and CardMedia components in my app but can't figure out how to overlay text on top of the image. This is a simplified example of what I'm trying:

<Card>
   <CardMedia image={this.props.preview} style={styles.media}/>
   <div style={styles.overlay}>
      this text should overlay the image
   </div>
</Card>


const styles = {
   media: {
      height: 0,
      paddingTop: '56.25%' // 16:9
   },
   overlay: {
      position: 'relative',
      top: '20px',
      left: '20px',
      color: 'black',
      backgroundColor: 'white'
   }
}

I've tried placing the text div in above the CardMedia, below it, inside it, outside the Card entirely, and using different position values but can't figure this out at all. The beta versions of MUI included an overlay property on the CardMedia, but the v1 library doesn't seem to have anything like that.

Any know how to properly do this? Thanks in advance for any help!

like image 854
Egor Egorov Avatar asked Jul 11 '18 21:07

Egor Egorov


Video Answer


1 Answers

Use the code below if you want to have an overlay like the Card in version 0. Remember to set the position of the container to relative so the absolute position of the overlay can take effect:

<Card sx={{ maxWidth: 345 }}>
  <Box sx={{ position: 'relative' }}>
    <CardMedia
      component="img"
      height="200"
      image="https://mui.com/static/images/cards/contemplative-reptile.jpg"
    />
    <Box
      sx={{
        position: 'absolute',
        bottom: 0,
        left: 0,
        width: '100%',
        bgcolor: 'rgba(0, 0, 0, 0.54)',
        color: 'white',
        padding: '10px',
      }}
    >
      <Typography variant="h5">Lizard</Typography>
      <Typography variant="body2">Subtitle</Typography>
    </Box>
  </Box>
  {...}
</Card>

1

Codesandbox Demo

like image 137
NearHuscarl Avatar answered Oct 31 '22 01:10

NearHuscarl