Html 如何使用 CSS 将文本覆盖在另一个文本上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9775853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:14:56  来源:igfitidea点击:

How can I overlay a text over another using CSS?

htmlcss

提问by eric01

I have this html file where I want to overlay some text over another. I tried to use the z-index property but can't get it to work. What is missing in my code?

我有这个 html 文件,我想在其中覆盖一些文本。我尝试使用 z-index 属性,但无法使其正常工作。我的代码中缺少什么?

thanks a lot

多谢

Here is the code

这是代码

<html>
<head>
<style>
#overlay {
    z-index:100;
}
</style>

</head>
<body>
<div id='overlay'>overlayed text</div>

This is some dummy text

</body>
</html>

采纳答案by Mario Aguilera

You need to set position: absolute. The z-indexapplies to elements that aren't statically positioned (see BoltClock's comment).

您需要设置position: absolute. 在z-index适用于不是静态定位的元素(见BoltClock的评论)。

<html>
<head>
<style>
#overlay {
    background-color: #EEEEEE;
    position: absolute;
    z-index:100;
}
</style>

</head>
<body>
<div id='overlay'>overlayed text</div>

This is some dummy text

</body>
</html>

回答by raison

You can do this with CSS alone by making use of :before

您可以通过使用 :before 单独使用 CSS 来完成此操作

img.image:before {
    left: 0;
    content: "Coming Soon";
    background: rgba(255, 255, 255, 0.59);
    color: #000;
    width: 100%;
    height: 100%;
    line-height: 2.5;
    font-weight: 600;
   position: absolute; 

}

回答by bhamlin

z-indexonly applies to elements with position:relativeor position:absolute. In your case you'll be wanted to use position:absoluteto place the overlayed text.

z-index仅适用于带有position:relative或 的元素position:absolute。在您的情况下,您将需要position:absolute用来放置覆盖的文本。