【问题标题】:Opacity in CSS applying to child divCSS中的不透明度应用于子div
【发布时间】:2017-08-05 17:43:15
【问题描述】:

关于 CSS 中 opacity 属性的问题。 我有一个带有标题的标题,并且应用了 0.3 的不透明度(以及过渡,但这不是问题所在)。 这是一个gif:

现在,我喜欢标题的效果,你可以清楚地看到它后面的图像,但我希望标题本身显示为白色,不透明度为 1。由于应用于其父 div 的不透明度,标题,它看起来像 div 的其余部分一样褪色。 有没有办法做到这一点?换句话说,有没有办法“覆盖”父元素的不透明度?

html,
body {
  margin: 0px;
  padding: 0px;
  height: 100vh;
}

#header {
  position: absolute;
  width: 100vw;
  height: 0vh;
  background-color: black;
  opacity: 0;
  z-index: 6;
  transition: height 1s ease, opacity 1s ease;
}

#hoverable {
  position: absolute;
  height: 10vh;
  width: 100%;
  z-index: 7;
}

#hoverable:hover #header {
  opacity: .3;
  height: 10vh;
}

#title {
  margin-left: 10vw;
  line-height: 10vh;
  float: left;
}
<div id="hoverable">
  <div id="header">
    <div id="title">
      <h1>TITLE</h1>
    </div>
  </div>
</div>

【问题讨论】:

标签: html css colors opacity


【解决方案1】:

您可以使用background-color: rgba(0,0,0,0);background-color: rgba(0,0,0,.3); 代替不透明度

RGBA代表红绿蓝阿尔法

html,
body {
  margin: 0px;
  padding: 0px;
  height: 100vh;
}

#header {
  position: absolute;
  width: 100vw;
  height: 0vh;
  background-color: rgba(0,0,0,0);
  z-index: 6;
  transition: height 1s ease, background 1s ease;
}

#hoverable {
  position: absolute;
  height: 10vh;
  width: 100%;
  z-index: 7;
}

#hoverable:hover #header {
  background-color: rgba(0, 0,0,.3);
  height: 10vh;
}

#title {
  margin-left: 10vw;
  line-height: 10vh;
  float: left;
}
<div id="hoverable">
  <div id="header">
    <div id="title">
      <h1>TITLE</h1>
    </div>
  </div>
</div>

【讨论】:

    【解决方案2】:

    我看到您正在为您的 div 使用 Id。也许你可以改用类。

    CSS 文件中的样式应该是“级联”的。因此,理论上,这应该允许样式表中稍后声明的样式覆盖之前声明的样式。但由于更具体的选择器(如 ID),这不会像我们希望的那样经常发生。

    例如,如果您有以下 HTML:

    <div id="element" class="element">
    <!-- stuff goes here... -->
    </div>
    

    还有 CSS:

    #element {
    background: blue;
    }
    
    body div.element {
    background: green;
    }
    

    尽管body div.element 选择器出现在#element ID 选择器之后,并且尽管“body”元素作为选择器的一部分包含在内,但元素的背景仍将是蓝色——而不是绿色——因为ID 选择器比第二个选择器更具体,自然级联已被覆盖。

    https://www.impressivewebs.com/difference-class-id-css/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2011-07-06
      • 2011-05-13
      相关资源
      最近更新 更多