【问题标题】:MUI Card text overlayMUI 卡文本覆盖
【发布时间】:2018-07-11 21:33:03
【问题描述】:

我在我的应用程序中使用 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 reactjs overlay material-ui


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您想要像Card in version 0 这样的叠加层,请使用下面的代码。记得将容器的位置设置为relative,这样覆盖的absolute位置才能生效:

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

      【讨论】:

        猜你喜欢
        • 2020-12-13
        • 2021-10-22
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2023-02-26
        • 2020-03-04
        • 2021-11-21
        • 2020-01-21
        相关资源
        最近更新 更多