为什么将 html 元素的不透明度更改为 0.5 后,无法将 h1 元素的不透明度更改回 1?

koz*_*koz 6 html css opacity

我在 css 中向 html 元素添加了背景图像,以便它随着 Web 浏览器的大小而扩展。我将此 html 元素中的不透明度更改为 0.5。我想将子元素(特别是 h1 和段落元素)更改回不透明度 1,以便文本不透明。这不起作用。请帮忙 :)

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <link rel = "stylesheet" href = "style.css">
</head>

<body>

    <p id ="topBar"></p>

    <h1>Heading</h1>

    <h3>Name</h3>

    <p> 
        Paragraph
    </p>

    <h3>Heading</h3>

    <p>More text</p>

    <h3>Send us an email!</h3>

    <form>
        <input style ="width:200px" type="email" placeholder ="Email" name="email"><br><br>
        <textarea style ="height:100px;width:200px"placeholder = "Message" name="message"></textarea><br><br>
        <input type="submit" value ="Send" name="send">
    </form>

    <p id ="bottomBar"></p>
</body>
 </html>
Run Code Online (Sandbox Code Playgroud)

CSS:

html {

background: url(pen.jpg) no-repeat center fixed;
background-size: cover;


font-family: Garamond;
text-align: center;

opacity: 0.5;

}

h1 {

opacity: 1;
 }
Run Code Online (Sandbox Code Playgroud)

Mih*_*i T 0

如果将父元素的不透明度设置为0.5,则所有子元素都将获得该不透明度。我建议您使用透明的 img 作为背景,或者您可以将该背景赋予伪元素。

(我使用背景颜色作为示例,但您可以使用background-imageandopacity:0.5代替。它仍然有效)

html {




font-family: Garamond;
text-align: center;


position:relative;


}
html:before {
  height:100%;
  width:100%;
  position:absolute;
  top:0;
  left:0;
  margin:0 auto;
  background:rgba(0,0,0,0.5);
   
  content:"";
  z-index:-1;
}

h1 {

opacity: 1;
 }
Run Code Online (Sandbox Code Playgroud)
 <p id ="topBar"></p>

    <h1>Heading</h1>

    <h3>Name</h3>

    <p> 
        Paragraph
    </p>

    <h3>Heading</h3>

    <p>More text</p>

    <h3>Send us an email!</h3>

    <form>
        <input style ="width:200px" type="email" placeholder ="Email" name="email"><br><br>
        <textarea style ="height:100px;width:200px"placeholder = "Message" name="message"></textarea><br><br>
        <input type="submit" value ="Send" name="send">
    </form>

    <p id ="bottomBar"></p>
Run Code Online (Sandbox Code Playgroud)