背景颜色的不透明度,但不是文本

时间:2009-03-12 09:51:09

标签: css opacity

如果文本保持不透明,如何为div的背景设置跨浏览器(包括Internet Explorer 6)透明度?

我需要在不使用任何库(如jQuery等)的情况下执行此操作。(但如果您知道有一个库,我很乐意知道,所以我可以查看他们的代码。)

5 个答案:

答案 0 :(得分:586)

使用rgba!

.alpha60 {
    /* Fallback for web browsers that don't support RGBa */
    background-color: rgb(0, 0, 0);
    /* RGBa with 0.6 opacity */
    background-color: rgba(0, 0, 0, 0.6);
    /* For IE 5.5 - 7*/
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}
  

除此之外,您还必须为IE网络浏览器声明background: transparent,最好通过条件评论或类似方式提供!

通过http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/

答案 1 :(得分:32)

我使用alpha透明的PNG:

div.semi-transparent {
  background: url('semi-transparent.png');
}

对于IE6,您需要使用PNG修补程序(12)。

答案 2 :(得分:16)

我已在我的博客Landman Code上创建了该效果。

我做的是

#Header {
  position: relative;
}
#Header H1 {
  font-size: 3em;
  color: #00FF00;
  margin:0;
  padding:0;
}
#Header H2 {
  font-size: 1.5em;
  color: #FFFF00;
  margin:0;
  padding:0;
}
#Header .Background {
  background: #557700;
  filter: alpha(opacity=30);
  filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
  -moz-opacity: 0.30;
  opacity: 0.3;
  zoom: 1;
}
#Header .Background * {
  visibility: hidden; // hide the faded text
}
#Header .Foreground {
  position: absolute; // position on top of the background div
  left: 0;
  top: 0;
}
<div id="Header">
  <div class="Background">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
  <div class="Foreground">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
</div>

重要的是每个填充/边距和内容在.Background和.Foreground都必须相同。

答案 3 :(得分:13)

放宽您对IE6和旧版浏览器的需求,您可以使用:: before和display:inline-block

div
{
  display: inline-block;
  position: relative;    
}
div::before
{
  content: "";
  display: block;
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  background:red;
  opacity: .2;
}

http://jsfiddle.net/KVyFH/172/的演示

它适用于任何现代浏览器

答案 4 :(得分:0)

感谢@ davy-landmann https://stackoverflow.com/a/638064/417153。 这就是我在寻找的东西!与LESS代码相同的效果:

  @searchResultMinHeight = 200px;
  .searchResult {
    min-height: @searchResultMinHeight;

    position: relative;
    .innerTrans {
      background: white;
      .opacity(0.5);
      min-height: @searchResultMinHeight;
    }
    .innerBody {
      padding: 0.5em;
      position: absolute;
      top: 0;
    }
  }