仅使用CSS,是否可以使元素的背景半透明,但元素的内容(文本和图像)不透明?

我想在不将文本和背景作为两个独立元素的情况下完成这一点。

尝试时:

p型{位置:绝对;背景色:绿色;过滤器:alpha(不透明度=60);不透明度:0.6;}跨度{颜色:白色;过滤器:alpha(不透明度=100);不透明度:1;}<p><span>你好,世界</span></p>

看起来子元素受到其父元素的不透明度的影响,因此不透明度:1相对于父元素的不可见性:0.6。


当前回答

可以使用附加到十六进制值的不透明度值:

background-color: #11ffeeaa;

在本例中,aa是不透明度。不透明度为00表示透明,ff表示纯色。

不透明度是可选的,因此可以一如既往地使用十六进制值:

background-color: #11ffee;

您也可以使用rgba()的旧方法:

background-color: rgba(117, 190, 218, 0.5);

如果您想确保背景没有其他样式,如图像或渐变,请使用背景速记:

background: #11ffeeaa;

根据Mozilla规范(https://developer.mozilla.org/en-US/docs/Web/CSS/background-color):

/* Keyword values */
background-color: red;
background-color: indigo;

/* Hexadecimal value */
background-color: #bbff00;    /* Fully opaque */
background-color: #bf0;       /* Fully opaque shorthand */
background-color: #11ffee00;  /* Fully transparent */
background-color: #1fe0;      /* Fully transparent shorthand  */
background-color: #11ffeeff;  /* Fully opaque */
background-color: #1fef;      /* Fully opaque shorthand  */

/* RGB value */
background-color: rgb(255, 255, 128);        /* Fully opaque */
background-color: rgba(117, 190, 218, 0.5);  /* 50% transparent */

/* HSL value */
background-color: hsl(50, 33%, 25%);         /* Fully opaque */
background-color: hsla(50, 33%, 25%, 0.75);  /* 75% transparent */

/* Special keyword values */
background-color: currentcolor;
background-color: transparent;

/* Global values */
background-color: inherit;
background-color: initial;
background-color: unset;

其他回答

这给出了所需的结果-

body {
    background-image: url("\images\dark-cloud.jpg");
    background-size: 100% 100%;
    background-attachment: fixed;
    opacity: .8;
}

设置背景的不透明度。

我同意以上所有的答案,rgba是正确的选择。在我的例子中,我以编程方式提供了一个十六进制背景,因此我必须基于十六进制代码生成自己的rgba。我创建了唐先生答案的修改版本,将十六进制转换为rgba

function hexToRgba(hex,alpha) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    if(result!=null){
      const r = parseInt(result[1], 16);
      const g = parseInt(result[2], 16);
      const b = parseInt(result[3], 16);
      //
      return `rgba(${r},${g},${b},${alpha})`;

    }
    return null;
  }

当使用#AARGGBB格式时,它对我有效,因此对我有效的格式是#1C00ff00。试试看,因为我看到它对某些人有效,而对其他人无效。我在CSS中使用它。

问题是,在您的示例中,文本实际上是完全不透明的。它在p标记内具有完全不透明性,但p标记只是半透明的。

您可以添加半透明的PNG背景图像,而不是在CSS中实现,或者将文本和div分离为两个元素,并将文本移动到框上(例如,负边距)。

否则就不可能了。

正如Chris所提到的:如果你使用一个具有透明度的PNG文件,你必须使用JavaScript解决方法来让它在烦人的Internet Explorer中工作。。。

这里有一个jQuery插件Transify(Transify-一个jQueryplugin,可以轻松地将透明度/不透明度应用于元素的背景),它可以为您处理所有事情。

我时不时地遇到这个问题,所以我决定写一些能让生活更轻松的东西。该脚本小于2KB,只需要一行代码就可以运行,如果您愿意,它还可以处理背景的不透明度动画。