Get text over an image using CardMedia (MUI)

k w
1 min readMar 8, 2021

--

Card rendered (image: https://pixabay.com/pl/photos/nale%C5%9Bniki-syrop-klonowy-sweet-2291908/)

Creating simple card with text

In order to put text over a picture you first need to put your CardMedia component inside a div and give the whole display:relative (property).

Next create another div block within the previous. As we know the positioning of an element with an absolute position is done relative to the first relatively (or absolutely) positioned parent element. So we can easily place our text on the picture in the desired place. We do not need to change how the picture is placed (by default it has position static).

In the example below the child element (our text) moves relative to the parent element by 50% left and top of the parent element by 10px. By adding translateX(-50%) we horizontally align text.

import React from "react";
import Card from "@material-ui/core/Card";
import {CardMedia} from "@material-ui/core";
const SimpleCard: React.FC<any> = (props) => {return (
<Card className={classes.root}>
<div style={{ position: "relative" }}>
<CardMedia style={{ height: "250px", paddingTop: "2%" }} component="img" image={"/pancakes.jpg"} title="Pancakes" alt="Pancakes"/>
<div style={{position: "absolute", color: "white",top: 10,left: "50%",transform: "translateX(-50%)",}}> Some text</div>
</div>
</Card>
)};export default SimpleCard;

--

--