最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set background to overlay text in next js? - Stack Overflow

programmeradmin6浏览0评论

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.

Checkout this issue live here.

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

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.

Checkout this issue live here.

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

Share Improve this question edited Feb 2, 2023 at 7:22 Mayank Kumar Chaudhari asked Jun 27, 2021 at 7:15 Mayank Kumar ChaudhariMayank Kumar Chaudhari 18.9k13 gold badges70 silver badges155 bronze badges 1
  • Thanks for the suggestion. But it did not work. Also, I should not be required to add z-index. I just added to test to see if it makes any difference. – Mayank Kumar Chaudhari Commented Jun 27, 2021 at 7:20
Add a ment  | 

2 Answers 2

Reset to default 4

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./100x80"/>
<p>Test without positioning</p>

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

Thanks to ment 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.

发布评论

评论列表(0)

  1. 暂无评论