14

I'm using the Material UI 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!

Olivier Tassinari
  • 8,238
  • 4
  • 23
  • 23
Egor Egorov
  • 705
  • 3
  • 10
  • 22

2 Answers2

16

Your CSS is off, you'll want to absolutely position the styles.overlay, and make sure the Card is position relative

Try something like this:

<Card style={styles.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
   },
   card: {
      position: 'relative',
   },
   overlay: {
      position: 'absolute',
      top: '20px',
      left: '20px',
      color: 'black',
      backgroundColor: 'white'
   }
}
jmancherje
  • 6,439
  • 8
  • 36
  • 56
12

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

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230