11

我想要div一个透明的背景。
我尝试使用background-colorand来做到这一点opacity,但问题是边框和里面的文本也变得透明了。这里的例子。

这是否可以在不使用透明 PNG 背景图像的情况下实现?

4

5 回答 5

20

如果您只希望背景的颜色是透明的而不是子内容,请使用

background-color: rgba(0,0,0,.5); // Sets to 50% transparent

有关更多详细信息,请参阅此页面 - 这是一个 css3 规范,因此不会出现在每个浏览器中:

http://www.css3.info/introduction-opacity-rgba/

于 2010-07-11T12:30:51.650 回答
6

是的。

background-color: transparent;

并且不要使用opacity,因为这就是使整个 div 半透明的原因。

在http://jsfiddle.net/eU7By/1/更新了您的示例

评论后更新

正如@DHuntrods 提到的,您可以使用 rgba 作为背景颜色。IE 当然需要一些调整.. http://leaverou.me/2009/02/bulletproof-cross-browser-rgba-backgrounds/

于 2010-07-11T12:00:41.013 回答
1

最跨浏览器的解决方案是在附加的“绝对定位”子元素(在相对或绝对定位的父元素中)上使用 opacity 属性:它只包含彩色透明背景。

然后您可以使用该opacity属性使该元素透明。由于该元素没有子元素,因此不透明度不会影响任何其他元素。

Opacity 是一个 IE5+ 属性,只需使用(参见http://css-tricks.com/snippets/css/cross-browser-opacity/):

-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";    /* IE 8 */
filter: alpha(opacity=50);  /* IE 5-7 */
-moz-opacity: 0.5;          /* Netscape */
-khtml-opacity: 0.5;        /* Safari 1.x */
opacity: 0.5;               /* Good browsers */

请参阅 jsFiddle 示例http://jsfiddle.net/DUjzX/1/

整个代码如下所示:

的HTML:

 <div class="my-cool-wrapper">
      <div class="text-and-images-on-top">
           <p>Here some content (text AND images) "on top of the transparent background"</p>
           <img src="http://i.imgur.com/LnnghmF.gif">
      </div>
      <div class="transparent-background">
      </div>
 </div>

CSS:

 .my-cool-wrapper {
      position: relative;
 }
 .my-cool-wrapper .text-and-images-on-top {
      padding: 10px 15px 19px 15px;
      z-index: 1;
      position: relative; /* needed to enable the z-index */
 }
 .my-cool-wrapper .transparent-background {
      position: absolute;
      top: 0;    
      width: 100%;
      height: 100%;
      -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=10)";       /* IE 8 */
      filter: alpha(opacity=10);  /* IE 5-7 */
      -moz-opacity: 0.1;          /* Netscape */
      -khtml-opacity: 0.1;        /* Safari 1.x */
      opacity: 0.1;               /* Good browsers */
      background-color: blue;
 }

阅读更多: 在不影响子元素的情况下设置背景图像的不透明度

截图证明 IE7 IE8 IE9 IE10 IE11

ps:我没有添加 Chrome、Firefox 和 Safari 的屏幕截图,因为这些是“更好”的浏览器……相信我,它也适用于它们。

于 2014-02-24T10:08:55.380 回答
0

我必须使用 30x30 的透明 gif 作为背景。

background:url('absolute path here');
于 2011-06-06T08:06:44.360 回答
0

这段代码是一个非常简单的在 html 中具有清晰透明背景的 CSS 方法。

background: rgba(0, 0, 0, 0.6)!important;
于 2022-02-01T07:40:54.843 回答