Html 如何使用 CSS 为文本或图像提供透明背景?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/806000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:41:46  来源:igfitidea点击:

How do I give text or an image a transparent background using CSS?

htmlcssopacity

提问by Stijn Sanders

Is it possible, using CSS only, to make the backgroundof an element semi-transparent but have the content (text & images) of the element opaque?

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

I'd like to accomplish this without having the text and the background as two separate elements.

我想在不将文本和背景作为两个单独的元素的情况下完成此操作。

When trying:

尝试时:

p {
  position: absolute;
  background-color: green;
  filter: alpha(opacity=60);
  opacity: 0.6;
}

span {
  color: white;
  filter: alpha(opacity=100);
  opacity: 1;
}
<p>
  <span>Hello world</span>
</p>

It looks like child elements are subjected to the opacity of their parents, so opacity:1is relative to the opacity:0.6of the parent.

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

采纳答案by Georg Sch?lly

Either use a semi-transparent PNGimage or use CSS 3:

要么使用半透明的PNG图像,要么使用 CSS 3:

background-color: rgba(255, 0, 0, 0.5);

Here's an article from css3.info, Opacity, RGBA and compromise(2007-06-03).

这是来自 css3.info、Opacity、RGBA 和妥协(2007-06-03)的一篇文章。



<p style="background-color: rgba(255, 0, 0, 0.5);">
  <span>Hello, World!</span>
</p>

回答by Sebastian Markb?ge

In Firefox 3 and Safari 3, you can use RGBA like Georg Sch?lly mentioned.

在 Firefox 3 和 Safari 3 中,您可以像Georg Sch?lly 提到的那样使用 RGBA 。

A little known trick is that you can use it in Internet Explorer as well using the gradient filter.

一个鲜为人知的技巧是,您也可以在 Internet Explorer 中使用渐变过滤器。

background-color: rgba(0, 255, 0, 0.5);
filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#7F00FF00', EndColorStr='#7F00FF00');

The first hex number defines the alpha value of the color.

第一个十六进制数定义颜色的 alpha 值。

Full solution all browsers:

所有浏览器的完整解决方案:

.alpha60 {
    /* Fallback for web browsers that doesn't support RGBa */
    background: rgb(0, 0, 0) transparent;
    /* RGBa with 0.6 opacity */
    background: 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)";
}

This is from CSS background transparency without affecting child elements, through RGBa and filters.

这是来自CSS 背景透明度而不影响子元素,通过 RGBa 和过滤器

Screenshots proof of results:

结果截图证明:

This is when using the following code:

这是使用以下代码时:

 <head>
     <meta http-equiv="X-UA-Compatible" content="IE=edge" >
    <title>An XHTML 1.0 Strict standard template</title>
     <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <style type="text/css" media="all">
         .transparent-background-with-text-and-images-on-top {
             background: rgb(0, 0, 0) transparent;   /* Fallback for web browsers that doesn't support RGBa */
            background: rgba(0, 0, 0, 0.6);   /* RGBa with 0.6 opacity */
             filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);  /* For IE 5.5 - 7*/
            -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";  /* For IE 8*/
         }
     </style>
 </head>

 <body>
     <div class="transparent-background-with-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>
 </body>
 </html>

Chrome-33IE11IE9IE8

铬 33IE11IE9IE8

回答by Gorkem Pacaci

This is the best solution I could come up with, NOT using CSS 3. And it works great on Firefox, Chrome and Internet Explorer as far as I can see.

这是我能想到的最好的解决方案,不使用 CSS 3。据我所知,它在 Firefox、Chrome 和 Internet Explorer 上运行良好。

Put a container DIV and two child DIVs in the same level, one for content, one for background. And using CSS, auto-size the background to fit the content and put the background actually in the back using z-index.

将一个容器 DIV 和两个子 DIV 放在同一级别,一个用于内容,一个用于背景。并使用 CSS 自动调整背景大小以适应内容,并使用 z-index 将背景实际放在后面。

.container {
  position: relative;
}
.content {
  position: relative;
  color: White;
  z-index: 5;
}
.background {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: Black;
  z-index: 1;
  /* These three lines are for transparency in all browsers. */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
  filter: alpha(opacity=50);
  opacity: .5;
}
<div class="container">
  <div class="content">
    Here is the content.
    <br/>Background should grow to fit.
  </div>
  <div class="background"></div>
</div>

回答by Slipp D. Thompson

For a simple semi-transparent background color, the above solutions (CSS3 or bg images) are the best options. However, if you want to do something fancier (e.g. animation, multiple backgrounds, etc.), or if you don't want to rely on CSS3, you can try the “pane technique”:

对于简单的半透明背景颜色,上述解决方案(CSS3 或 bg 图像)是最佳选择。但是,如果你想做一些更高级的事情(例如动画、多背景等),或者如果你不想依赖 CSS3,你可以尝试“窗格技术”:

.pane, .pane > .back, .pane > .cont { display: block; }

.pane {
    position: relative;
}

.pane > .back {
    position: absolute;
    width: 100%; height: 100%;
    top: auto; bottom: auto; left: auto; right: auto;
}

.pane > .cont {
    position: relative;
    z-index: 10;
}
<p class="pane">
    <span class="back" style="background-color: green; opacity: 0.6;"></span>
    <span class="cont" style="color: white;">Hello world</span>
</p>

The technique works by using two “layers” inside of the outer pane element:

该技术通过在外部窗格元素内部使用两个“层”来工作:

  • one (the “back”) that fits the size of the pane element without affecting the flow of content,
  • and one (the “cont”) that contains the content and helps determine the size of the pane.
  • 一个(“背面”)适合窗格元素的大小而不影响内容的流动,
  • 和一个(“cont”)包含内容并帮助确定窗格的大小。

The position: relativeon pane is important; it tells back layer to fit to the pane's size. (If you need the <p>tag to be absolute, change the pane from a <p>to a <span>and wrap all that in a absolutely-position <p>tag.)

position: relative上面板是很重要的; 它告诉后层适合窗格的大小。(如果您需要<p>绝对标签,请将窗格从 a 更改<p>为 a<span>并将所有内容包装在绝对位置<p>标签中。)

The main advantage this technique has over similar ones listed above is that the pane doesn't have to be a specified size; as coded above, it will fit full-width (normal block-element layout) and only as high as the content. The outer pane element can be sized any way you please, as long as it's rectangular (i.e. inline-block will work; plain-old inline will not).

与上面列出的类似技术相比,这种技术的主要优点是窗格不必具有指定的大小;如上面的编码,它将适合全宽(正常的块元素布局)并且仅与内容一样高。外部窗格元素可以按您喜欢的任何方式调整大小,只要它是矩形的(即 inline-block 可以工作;plain-old inline 不行)。

Also, it gives you a lot of freedom for the background; you're free to put really anything in the back element and have it not affect the flow of content (if you want multiple full-size sub-layers, just make sure they also have position: absolute, width/height: 100%, and top/bottom/left/right: auto).

此外,它为您提供了很大的背景自由度;你可以自由地在后面的元素中放置任何东西,并且不会影响内容的流动(如果你想要多个全尺寸的子层,只要确保它们也有位置:绝对,宽度/高度:100%,和上/下/左/右:自动)。

One variation to allow background inset adjustment (via top/bottom/left/right) and/or background pinning (via removing one of the left/right or top/bottom pairs) is to use the following CSS instead:

允许背景插入调整(通过上/下/左/右)和/或背景固定(通过删除左/右或上/下对之一)的一种变体是使用以下 CSS:

.pane > .back {
    position: absolute;
    width: auto; height: auto;
    top: 0px; bottom: 0px; left: 0px; right: 0px;
}

As written, this works in Firefox, Safari, Chrome, IE8+, and Opera, although IE7 and IE6 require extra CSS and expressions, IIRC, and last time I checked, the second CSS variation does not work in Opera.

正如所写,这适用于 Firefox、Safari、Chrome、IE8+ 和 Opera,尽管 IE7 和 IE6 需要额外的 CSS 和表达式、IIRC,并且上次我检查过,第二个 CSS 变体在 Opera 中不起作用。

Things to watch out for:

需要注意的事项:

  • Floating elements inside of the cont layer will not be contained. You'll need to make sure they are cleared or otherwise contained, or they'll slip out of the bottom.
  • Margins go on the pane element and padding goes on the cont element. Don't do use the opposite (margins on the cont or padding on the pane) or you'll discover oddities such as the page always being slightly wider than the browser window.
  • As mentioned, the whole thing needs to be block or inline-block. Feel free to use <div>s instead of <span>s to simplify your CSS.
  • 将不包含 cont 层内的浮动元素。您需要确保它们被清除或以其他方式包含在内,否则它们会从底部滑出。
  • 边距位于窗格元素上,填充位于 cont 元素上。不要使用相反的方式(连续页上的边距或窗格上的填充),否则您会发现一些奇怪的现象,例如页面总是比浏览器窗口稍宽。
  • 如前所述,整个事情需要是块或内联块。随意使用<div>s 而不是<span>s 来简化您的 CSS。


A fuller demo, showing off the flexiblity of this technique by using it in tandem with display: inline-block, and with both auto& specific widths/min-heights:

一个更完整的演示,展示了这种技术的灵活性,将它与display: inline-block, 和auto特定的widths/ min-heights 一起使用:

.pane, .pane > .back, .pane > .cont { display: block; }
.pane {
 position: relative;
 width: 175px; min-height: 100px;
 margin: 8px;
}

.pane > .back {
 position: absolute; z-index: 1;
 width: auto; height: auto;
 top: 8px; bottom: 8px; left: 8px; right: 8px;
}

.pane > .cont {
 position: relative; z-index: 10;
}

.debug_red { background: rgba(255, 0, 0, 0.5); border: 1px solid rgba(255, 0, 0, 0.75); }
.debug_green { background: rgba(0, 255, 0, 0.5); border: 1px solid rgba(0, 255, 0, 0.75); }
.debug_blue { background: rgba(0, 0, 255, 0.5); border: 1px solid rgba(0, 0, 255, 0.75); }
<p class="pane debug_blue" style="float: left;">
 <span class="back debug_green"></span>
 <span class="cont debug_red">
  Pane content.<br/>
  Pane content.
 </span>
</p>
<p class="pane debug_blue" style="float: left;">
 <span class="back debug_green"></span>
 <span class="cont debug_red">
  Pane content.<br/>
  Pane content.<br/>
  Pane content.<br/>
  Pane content.<br/>
  Pane content.<br/>
  Pane content.<br/>
  Pane content.<br/>
  Pane content.<br/>
  Pane content.
 </span>
</p>
<p class="pane debug_blue" style="float: left; display: inline-block; width: auto;">
 <span class="back debug_green"></span>
 <span class="cont debug_red">
  Pane content.<br/>
  Pane content.
 </span>
</p>
<p class="pane debug_blue" style="float: left; display: inline-block; width: auto; min-height: auto;">
 <span class="back debug_green"></span>
 <span class="cont debug_red">
  Pane content.<br/>
  Pane content.
 </span>
</p>

And here's a live demoof the technique being used extensively:

这是广泛使用的技术的现场演示

christmas-card-2009.slippyd.com screenshot

christmas-card-2009.slippyd.com screenshot

回答by Slipp D. Thompson

It's better to use a semi-transparent .png.

最好使用半透明的.png.

Just open Photoshop, create a 2x2pixel image (picking 1x1can cause an Internet Explorer bug!), fill it with a green color and set the opacity in "Layers tab" to 60%. Then save it and make it a background image:

只需打开Photoshop,创建一个2x2像素图像(选择1x1会导致 Internet Explorer 错误!),用绿色填充它并将“图层选项卡”中的不透明度设置为 60%。然后保存它并使其成为背景图像:

<p style="background: url(green.png);">any text</p>

It works cool, of course, except in lovely Internet Explorer 6. There are better fixes available, but here's a quick hack:

当然,它很酷,除了在可爱的Internet Explorer 6 中。有更好的修复可用,但这里有一个快速黑客:

p {
    _filter: expression((runtimeStyle.backgroundImage != 'none') ? runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+currentStyle.backgroundImage.split('\"')[1]+', sizingMethod=scale)' : runtimeStyle.filter,runtimeStyle.backgroundImage = 'none');
}

回答by web-tiki

There is a trick to minimize the markup: Use a pseudo elementas the background and you can set the opacity to it without affecting the main element and its children:

有一个技巧可以最小化标记:使用伪元素作为背景,您可以为其设置不透明度,而不会影响主元素及其子元素:

DEMO

演示

Output:

输出:

Background opacity with a pseudo element

Background opacity with a pseudo element

Relevant code:

相关代码:

p {
  position: relative;
}
p:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
  opacity: .6;
  z-index: -1;
}
/*** The following is just for demo styles  ***/

body {
  background: url('http://i.imgur.com/k8BtMvj.jpg') no-repeat;
  background-size: cover;
}
p {
  width: 50%;
  padding: 1em;
  margin: 10% auto;
  font-family: arial, serif;
  color: #000;
}
img {
  display: block;
  max-width: 90%;
  margin: .6em auto;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a ligula ut nunc dignissim molestie.
  <img src="http://i.imgur.com/hPLqUtN.jpg" alt="" />
</p>

Browser support is Internet Explorer 8and later.

浏览器支持Internet Explorer 8及更高版本。

回答by Chris

The easiest method would be to use a semi-transparent background PNG image.

最简单的方法是使用半透明背景PNG 图像

You can use JavaScript to make it work in Internet Explorer 6if you need to.

如果需要,您可以使用 JavaScript 使其在Internet Explorer 6 中工作。

I use the method outlined in Transparent PNGs in Internet Explorer 6.

我使用Internet Explorer 6中的透明 PNG 中概述的方法。

Other than that, you could fake it using two side-by-side sibling elements- make one semi-transparent, then absolutely position the other over the top.

除此之外,您可以使用两个并排的兄弟元素来伪造它- 使一个半透明,然后将另一个绝对放置在顶部

回答by frozenkoi

This method allows you to have an image in the background and not only a solid color, and can be used to have transparency on other attributes such as borders. No transparent PNG images are required.

此方法允许您在背景中使用图像而不仅仅是纯色,并且可用于在其他属性(例如边框)上具有透明度。不需要透明的 PNG 图像。

Use :before(or :after) in CSS and give them the opacity value to leave the element at its original opacity. Thus you can use :before to make a faux element and give it the transparent background (or borders) you want and move it behind the content you want to keep opaque with z-index.

在 CSS 中使用:before(或:after) 并为它们提供不透明度值以使元素保持其原始不透明度。因此,您可以使用 :before 制作一个人造元素并为其提供所需的透明背景(或边框),并将其移动到您想要保持不透明的内容后面z-index

An example (fiddle) (note that the DIVwith class dadis just to provide some context and contrast to the colors, this extra element is actually not needed, and the red rectangle is moved a bit down and to the right to leave visible the background behind the fancyBgelement):

一个例子(小提琴)(注意DIVwith 类dad只是为了提供一些背景和颜色的对比,这个额外的元素实际上是不需要的,红色矩形向下和向右移动一点,让后面的背景可见的fancyBg元素):

<div class="dad">
    <div class="fancyBg">
        Test text that should have solid text color lets see if we can manage it without extra elements
    </div>
</div>

with this CSS:

使用这个 CSS:

.dad {
    background: lime; border: 1px double black; margin: 1ex 2ex;
    padding: 0.5ex; position: relative; -k-z-index: 5;
}
.fancyBg {
    border: 1px dashed black; position: relative; color: white; font-weight: bold;
    z-index: 0; /*background: black;*/
}
.fancyBg:before {content:'-'; display: block;
    position: absolute; background: red; opacity: .5;
    top: 2ex; right: -2ex; bottom: -2ex; left: 2ex;
    /*top: 0; right: 0; bottom: 0; left: 0;*/
    z-index: -1;
}

In this case .fancyBg:beforehas the CSS properties you want to have with transparency (red background in this example, but can be an image or borders). It's positioned as absolute to move it behind .fancyBg(use values of zero or whatever is more appropriate for your needs).

在这种情况下,.fancyBg:before具有您想要具有透明度的 CSS 属性(在此示例中为红色背景,但可以是图像或边框)。它被定位为绝对将它移到后面.fancyBg(使用零值或任何更适合您需要的值)。

回答by SvenFinke

The problem is, that the text actually hasfull opacity in your example. It has full opacity inside the ptag, but the ptag is just semi-transparent.

问题是,该文本实际上已经在你的例子完全不透明。它在p标签内部完全不透明,但p标签只是半透明的。

You could add an semi-transparent PNG background image instead of realizing it in CSS, or separate text and div into two elements and move the text over the box (for example, negative margin).

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

Otherwise it won't be possible.

否则就不可能了。

Just like Chris mentioned: if you use a PNG file with transparency, you have to use a JavaScript workaround to make it work in the pesky Internet Explorer...

就像 Chris 提到的:如果你使用透明的 PNG 文件,你必须使用 JavaScript 解决方法让它在讨厌的 Internet Explorer 中工作......

回答by thinsoldier

Almost all these answers assume the designer wants a solid color background. If the designer actually wants a photo as the background the only real solution at the moment is JavaScript like the jQuery Transify plugin mentioned elsewhere.

几乎所有这些答案都假设设计师想要纯色背景。如果设计师真的想要一张照片作为背景,那么目前唯一真正的解决方案是 JavaScript,就像其他地方提到的 jQuery Transify 插件。

What we need to do is join the CSS working group discussion and make them give us a background-opacity attribute! It should work hand in hand with the multiple-backgrounds feature.

我们需要做的是加入 CSS 工作组讨论,让他们给我们一个 background-opacity 属性!它应该与多背景功能齐头并进。