MUI 卡片文字叠加

MUI Card text overlay

我在我的应用程序中使用 MUI CardCardMedia 组件,但不知道如何在图像上叠加文本。这是我正在尝试的一个简化示例:

<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'
   }
}

我试过将文本 div 放在 CardMedia 上方、下方、里面、完全在卡片外面,并使用不同的位置值,但无法在全部。 MUI 的 Beta 版本在 CardMedia 上包含一个覆盖层 属性,但 v1 库似乎没有类似的内容。

有人知道如何正确执行此操作吗?在此先感谢您的帮助!

您的 CSS 已关闭,您需要绝对定位 styles.overlay,并确保 Card 位于 relative

位置

尝试这样的事情:

<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'
   }
}

如果您想要像 Card in version 0 这样的叠加层,请使用下面的代码。记得把container的position设置为relative这样overlay的absoluteposition才能生效:

<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>