How to set background to overlay text in next js?

Viewed 2734

I am creating an image element with overlay text. Here is my jsx code

<div className={styles.img}>
    <img src={src} alt="" />
    <p>{`(${size})`}</p>        
</div>

and here is sass

.img {
    min-width: 180px;
    text-align: center;
    cursor: pointer;
    img {
        height: 90px;
        box-shadow: orangered 0 0 5px;
    }
    p {
        color: white;
        font-weight: bold;
        margin: auto;
        font-size: .8rem;
        margin-top: - 1.6rem;
        // max-width: 120px;
        // z-index: 100;
        background-color: #0070f3;
    }
}

I get result as shown in following image. The background of p tag is visible only outside the img and not over the img.

enter image description here

Checkout this issue live here.

How do I show the background for overlay text on image so that it is readable?

2 Answers

You need to set the position to something other than the default value (static) in order to use z-index. Here's an example with position: relative.

p
{
background: #0cf;
margin-top: -1.6rem;
z-index: 100;
}

p.positioned
{
position: relative;
}
<img src="http://via.placeholder.com/100x80"/>
<p>Test without positioning</p>

<img src="http://via.placeholder.com/100x80"/>
<p class="positioned">Test with positioning</p>

Thanks to comment by @Devid.

Just to clarify, the position: relative should be added on the p tag. Adding position: relative to the container div does not make any difference.

Related