Text overlay on Material UI Card

I am currently using the Material UI Card and CardMedia components in my application, but I am having trouble with overlaying text on top of the image. Below is a simplified version of what I have been attempting:

<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 have attempted various placements for the text div such as above the CardMedia, below it, inside it, outside the Card entirely, and experimenting with different position values without success. The beta versions of MUI had an overlay property on the CardMedia, but the v1 library does not seem to have that feature.

If anyone has expertise in properly achieving this effect, I would greatly appreciate any guidance. Thank you in advance for your assistance!

Answer №1

Your layout needs some adjustments in the CSS department. To properly overlay text on an image, you must use absolute positioning for the styles.overlay, while ensuring that the Card is set to a relative position.

Consider using this code snippet as a starting point:

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

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

Answer №2

To achieve a similar overlay effect as the Card component in version 0, use the code snippet below. Make sure to set the container's position to relative for the absolute positioning of the overlay to work properly:

<Card sx={{ maxWidth: 345 }}>
  <Box sx={{ position: 'relative' }}>
    <CardMedia
      component="img"
      height="200"
      image="https://example.com/image.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">Title</Typography>
      <Typography variant="body2">Subtitle</Typography>
    </Box>
  </Box>
  {...}
</Card>

https://example.com/codesandbox-link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to choose a child div using jQuery

<div class='class1'> <div class='class2'> <div class='class3'> some unique text </div> <div class='class5'> more unique text </div> </div> < ...

Can you provide guidance on configuring the image class within a DOM element using echo?

What is the method to set the class attribute of an img element using echo function? <div class="allnis" style="padding: 15px; text-transform: uparcase;"> <?php foreach($tv_id->networks as $prod){ echo "<img val ...

Why isn't the background-image displaying with the use of the url() function?

I've been attempting to set an image as the background using background-img:url(imageLing), but it's not working properly. When I inspect the element, it shows me background-image: url(assets/backgrounds/5.jpg);. What could be causing this issue? ...

Fixing alignment and responsiveness problems with a hovering circle div

I have 3 circular divs that resize slightly when you hover over them, but this resizing also occurs if you hover near them. Additionally, I want them to be centered with some responsive spacing. Here is a live demo: demo Below is my code: <div id ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

Sidebar Text Remains Visible Despite Collapsed Sidebar

I'm working on implementing a sidebar shrink effect when collapsing it using a combination of custom CSS, jQuery, and Bootstrap. The custom CSS and jQuery handle the shrinking effect, while Bootstrap is used for styling purposes. However, I am facing ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

Redux - Preventing Overwriting of Product Quantity in Cart by Creating a New Object

Is there a way to address the issue where adding the same product multiple times to the cart creates new objects instead of increasing the quantity? switch (action.type) { case actionTypes.ADD_TO_CART: const product = state.products.find((p) = ...

Personalizing the design of Bootstrap

As a beginner in working with Bootstrap, I am currently focused on creating an index html page for an online shop. For reference, here is an example - https://jsfiddle.net/a393wtng/1/ Upon resizing the output frame, it becomes apparent that 4 products can ...

Error 404: Unable to locally install node.js npm due to ENOENT chmod

I ran into issues while attempting to execute npm install on a node/react application that I have taken over for development purposes. I am not looking to globally install any packages. My setup involves using an M1 Macbook Pro with Big Sur. I installed n ...

How can I present information stored in a MongoDB database on the client-side interface?

I developed a chat application using nodejs/express, mongodb, and reactjs. Despite successfully storing data in mongodb when the send button is clicked, I am facing difficulties displaying the data on the client side. Specifically, I am encountering issues ...

CodeIgniter functionality for generating auto-incrementing IDs that are accessible in both the view and within JavaScript's Window.Print() method

While working on creating an invoice, I encountered a few issues. First, I want the Invoice No: to be displayed in my view (receipt.php) as 0001 and use it as the primary key in my tbl_payment table. However, I'm unsure how to have an auto-incremented ...

Step-by-step guide on how to include the "content-based-recommender" package in a Reactjs project

I recently started learning React.js and I'm interested in using the "Content-Based Recommender" package from npm. However, after downloading it, I encountered an issue with importing it. The documentation suggests the following: const ContentBasedRec ...

Exploring the potential of nested arrays within checkbox inputs

I'm struggling with extracting a nested array from an input value of a checkbox. How should I handle this situation? Here are the values: const othersOptions = [ {procedure:'ORAL PROPHYLAXIS',price: 1000}, {procedure:'TOOTH RESTORATION ...

How can I define Record values in Typescript based on their specific keys?

I am working on creating a custom data structure that allows me to store values with string keys within the union string | number | boolean: type FilterKey = string; type FilterValue = string | number | boolean; type Filters<K extends FilterKey, T exten ...

The React app failed to compile on just my computer

Attempting to launch a React app using npm start results in a slew of errors related to the types: no-undef and no-restricted-globals. Strangely, the code compiles and runs perfectly fine on my colleagues' machines! I've synced up my npm and nod ...

Leveraging React's useEffect hook to asynchronously fetch and load data

In my coding scenario, there is a parent component containing a child component which loads data asynchronously. This is what I currently have: <Parent> <AsyncChild data={props.data} /> <Child /> </Parent> Within the AsyncChil ...

The measurement of Str's length combined with the presence of

When dealing with 2 input fields that specify a range of minimum and maximum numbers, I encountered an issue. Despite limiting the length of the string in the event.target.value within the inputChange functions, users are able to type multiple zeros beyond ...

The module 'react-bootstrap' does not have a 'Label' export available

Attempting npm start resulted in the following error message. ./src/App.js 104:16-24 'react-bootstrap' does not contain an export named 'Label'. How can this issue be resolved? I attempted to use npm install. Is there an alternative co ...

Utilizing Authorization Package for Server Side Rendering in Next.js

I've been grappling with a question regarding Next.js 14 and the Auth.js (Next-Auth) package. To access the status and data, we need to wrap the element in a <SessionProvider>. However, this comes with a caveat – SessionProvder must be within ...