代码之家  ›  专栏  ›  技术社区  ›  Stijn Sanders

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

  •  2095
  • Stijn Sanders  · 技术社区  · 16 年前

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

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

    尝试时:

    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>

    看起来子元素受到其父元素不透明度的影响,所以 opacity:1 是相对于 opacity:0.6 父母的

    28 回复  |  直到 6 年前
        1
  •  2177
  •   Georg Schölly    11 年前

    要么使用半透明的 PNG 图像或使用CSS3:

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

    这是css3.info的一篇文章, Opacity, RGBA and compromise (2007—06—03)。

        2
  •  465
  •   Adrien Be    8 年前

    在火狐3和Safari 3中,您可以使用类似rgba的 Georg Schölly mentioned .

    一个鲜为人知的诀窍是,你可以在Internet Explorer中使用它,也可以使用渐变过滤器。

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

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

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

    .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)";
    }
    

    这是来自 CSS background transparency without affecting child elements, through RGBa and filters .

    截图结果证明:

    这是在使用以下代码时:

     <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-33 IE11 IE9 IE8

        3
  •  102
  •   Ruslan López    10 年前

    这是我能想到的最好的解决方案,而不是使用CSS 3。据我所见,它在Firefox、Chrome和Internet Explorer上都非常有效。

    将一个容器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>
        4
  •  56
  •   Slipp D. Thompson Jon Brooks    6 年前

    对于简单的半透明背景色,上述解决方案(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>
    

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

    • 一个(“back”),适合窗格元素的大小,但不影响内容的流动,
    • 以及一个包含内容并帮助确定窗格大小的(“cont”)。

    这个 position: relative 在窗格上很重要;它告诉后面的层要适合窗格的大小。(如果您需要 <p> 标记为绝对,将窗格从 <P & GT; 到A <span> 把所有的东西都包在一个绝对的位置上 <P & GT; 标签)

    与上面列出的类似技术相比,此技术的主要优势在于窗格不必是指定的大小;如上所述,它将适合全宽(正常的块元素布局),并且仅与内容一样高。外窗格元素可以任意调整大小,只要它是矩形的(即内联块可以工作;普通的旧内联不会工作)。

    此外,它还为背景提供了很大的自由度;您可以自由地在back元素中放置真正的任何内容,并且不影响内容的流动(如果您想要多个全尺寸的子层,只需确保它们也具有位置:绝对、宽度/高度:100%和顶部/底部/左/右:自动)。

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

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

    如前所述,这在firefox、safari、chrome、ie8+和opera中有效,尽管ie7和ie6需要额外的css和expressions、iirc,而且上次我检查时,第二个css变体在opera中不起作用。

    注意事项:

    • 不包含控制层内的浮动元素。你需要确保它们被清除或者被其他方式控制,否则它们会滑出底部。
    • 页边距在pane元素上,填充在cont元素上。不要使用相反的页面(在控制面板上的页边距或填充),否则会发现一些奇怪的地方,比如页面总是比浏览器窗口略宽。
    • 如前所述,整个事情需要是块或内联块。随意使用 <div> S而不是 <SPAN & GT; 简化你的CSS。

    更全面的演示,通过与 display: inline-block 和两者兼而有之 auto 特异性 width S/ min-height S:

    .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>

    这是一个 live demo 广泛使用的技术:

    christmas-card-2009.slippyd.com screenshot

        5
  •  55
  •   Community CDub    8 年前

    最好用半透明的 .png .

    刚刚打开 Photoshop 创建一个 2x2 像素图像 picking 1x1 can cause an Internet Explorer bug! )将其填充为绿色,并将“图层选项卡”中的不透明度设置为60%。然后保存它并使其成为背景图像:

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

    当然,它很酷,除了可爱的 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');
    }
    
        6
  •  50
  •   Peter Mortensen icecrime    9 年前

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

    DEMO

    输出:

    Background opacity with a pseudo element

    相关代码:

    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>

    浏览器支持是 Internet Explorer 8 后来。

        7
  •  23
  •   KesaVan Aleksei Anufriev    10 年前

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

    您可以使用javascript使其在 Internet Explorer 6 如果你需要的话。

    我使用中概述的方法 Transparent PNGs in Internet Explorer 6 .

    除此之外,

    你可以用 two side-by-side sibling elements -使 一个半透明的 然后 absolutely position the other over the top ?

        8
  •  21
  •   Slipp D. Thompson Jon Brooks    9 年前

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

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

    一个例子( fiddle )(注意 DIV 随班 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>
    

    用这个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;
    }
    

    在这种情况下 .fancyBg:before 具有要具有透明度的CSS属性(本例中为红色背景,但可以是图像或边框)。它的位置是绝对的,可以向后移动。 .fancyBg (使用零值或更适合您需要的值)。

        9
  •  15
  •   Community CDub    8 年前

    几乎所有这些答案都假设设计师想要纯色背景。如果设计者真的想要一张照片作为背景,那么目前唯一真正的解决方案就是像jquery transify插件那样的javascript。 mentioned elsewhere .

    我们需要做的是加入CSS工作组讨论,让他们给我们一个背景不透明度属性!它应该与多背景功能一起工作。

        10
  •  14
  •   Peter Mortensen icecrime    14 年前

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

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

    否则就不可能了。

    编辑:

    就像克里斯提到的:如果你使用一个透明的PNG文件,你必须使用一个javascript解决方案,使它在烦人的Internet Explorer中工作…

        11
  •  13
  •   5 revs, 5 users 57%<br/>paris ionescu&#13;    10 年前

    以下是我如何做到这一点(这可能不是最佳的,但很有效):

    创建 div 你想要的是半透明的。给它一个类/ID。让它空着,然后关闭它。给它一个设定的高度和宽度(例如,300像素乘300像素)。给它0.5的不透明度或你喜欢的任何东西,和背景色。

    然后,在该分区的正下方,创建另一个具有不同类/ID的分区。在其中创建一个段落,在其中放置文本。给予 div 位置:相对,顶部: -295px (负295像素)。给它一个2的z指数作为好的度量,并确保它的不透明度是1。根据自己的喜好设置段落的样式,但要确保其尺寸小于第一个的尺寸。 div 所以不会溢出。

    就是这样。代码如下:

    .trans {
      opacity: 0.5;
      height: 300px;
      width: 300px;
      background-color: orange;
    }
    .trans2 {
      opacity: 1;
      position: relative;
      top: -295px;
    }
    .trans2 p {
      width: 295px;
      color: black;
      font-weight: bold;
    }
    <body>
      <div class="trans">
      </div>
      <div class="trans2">
        <p>
          text text text
        </p>
      </div>
    </body>

    这在Safari 2.x中有效,我不知道Internet Explorer。

        12
  •  12
  •   Peter Mortensen icecrime    14 年前

    这里有一个jquery插件,它将为您处理所有事情,transify( Transify - a jQuery plugin to easily apply transparency / opacity to an element’s background )

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

        13
  •  10
  •   Community CDub    8 年前

    Opacity of background, but not the text 有一些想法。要么使用半透明图像,要么覆盖一个附加元素。

        14
  •  10
  •   Peter Mortensen icecrime    14 年前

    不久前,我在 Cross Browser Background Transparency With CSS .

    奇怪的是,InternetExplorer6将允许您使背景透明,并使顶部的文本完全不透明。对于其他浏览器,我建议使用透明的PNG文件。

        15
  •  9
  •   Peter Mortensen icecrime    9 年前

    如果你是 Photoshop 伙计,你也可以用:

     #some-element {
      background-color: hsla(170, 50%, 45%, 0.9); // **0.9 is the opacity range from 0 - 1**
     }
    

    或:

    #some-element {
      background-color: rgba(170, 190, 45, 0.9); // **0.9 is the opacity range from 0 - 1**
    }
    
        16
  •  7
  •   DragonBear    12 年前

    背景色:RGBA(255,0,0,0.5); 如上所述,简单地说就是最好的答案。可以说,即使在2013年,使用CSS3也不简单,因为不同浏览器的支持级别会随着每次迭代的变化而变化。

    同时 background-color 所有主要浏览器都支持(不是CSS3的新版本)[1]alpha透明可能很棘手,特别是在9版之前的Internet Explorer和5.1版之前的Safari上的边框颜色。〔2〕

    使用类似 Compass SASS 可以真正帮助生产和跨平台的兼容性。


    〔1〕 W3Schools: CSS background-color Property

    〔2〕 Norman's Blog: Browser Support Checklist CSS3 (October 2012)

        17
  •  7
  •   Touhid Rahman    12 年前

    CSS3可以很容易地解决您的问题。用途:

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

    这里,rgba代表红色、绿色、蓝色和alpha值。绿色值是由于255而获得的,半透明度是由0.5α值获得的。

        18
  •  7
  •   Pushp Singh    9 年前

    为了使元素的背景半透明,但使元素的内容(文本和图像)不透明。您需要为该图像编写CSS代码,并且必须添加一个名为不透明度的最小值属性。 例如

    .image{
       position: relative;
       background-color: cyan;
      opacity: 0.7;
    }
    

    //越小值越透明,越少值越透明。

        19
  •  6
  •   Peter Mortensen icecrime    9 年前

    如果你在用 Less ,你可以使用 fade(color, 30%) .

        20
  •  4
  •   Peter Mortensen icecrime    9 年前

    你可以解决这个问题 Internet Explorer 8 使用渐变语法。颜色格式为argb。如果您正在使用 Sass 预处理器可以使用内置函数“ie-hex-str()”转换颜色。

    background: rgba(0,0,0, 0.5);
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#80000000')";
    
        21
  •  4
  •   Peter Mortensen icecrime    9 年前

    你可以用纯的 CSS 3 : rgba(red, green, blue, alpha) 在哪里 alpha 是您想要的透明度级别。不需要使用javascript或jquery。

    下面是一个例子:

    #item-you-want-to-style{
        background:rgba(192.233, 33, 0.5)
    }
    
        22
  •  3
  •   premgowda    10 年前
    <div align="center" style="width:100%;height:100%;background:white;opacity:0.5;position:absolute;z-index:1001">
        <img id="search_img" style="margin-top:20%;" src="../resources/images/loading_small.gif">
    </div>
    

    http://jsfiddle.net/x2ukko7u/ ?

        23
  •  1
  •   Peter Mortensen icecrime    9 年前

    有一个更简单的解决方案可以在同一个分区中的图像上加一个覆盖。这不是这个工具的正确使用。但它的工作方式就像一个魅力,可以使用CSS来制作覆盖。

    使用这样的插入阴影:

    box-shadow: inset 0 0 0 1000px rgba(255, 255, 255, 0.9);
    

    就是这样:

        24
  •  1
  •   Alireza    7 年前

    你可以使用 RGBA (red, green, blue, alpha) CSS ,如下所示:

    所以,简单地做一些这样的事情就可以了:

    p {
      position: absolute;
      background-color: rgba(0, 255, 0, 0.6);
    }
    
    span {
      color: white;
    }
    
        25
  •  0
  •   Cengkuru Michael    8 年前

    我通常把这门课用在工作上。很不错。

    .transparent {
      filter: alpha(opacity=50); /* internet explorer */
      -khtml-opacity: 0.5;      /* khtml, old safari */
      -moz-opacity: 0.5;       /* mozilla, netscape */
      opacity: 0.5;           /* fx, safari, opera */
    }
        26
  •  0
  •   Rudra    7 年前

    你可以用 rgba color code 使用类似下面给出的示例的CSS。

    .imgbox img{
      height:100px;
      width:200px;
      position:relative;
    }
    .overlay{
      background:rgba(74, 19, 61, 0.4);
      color:#fff;
      text-shadow:0px 2px 5px #000079;
      height:100px;
      width:300px;
      position:absolute;
      top:10%;
      left:25%;
      padding:25px;
    }
    <div class"imgbox">
    <img src="http://www.bhmpics.com/wallpapers/little_pony_art-800x480.jpg">
      <div class="overlay">
        <p>This is Simple Text.</p>
      </div>
    </div>
        27
  •  0
  •   Vinod Kumar    6 年前

    根据我的观点,使用不透明度背景色的最佳方法。如果我们使用此方法,则不会丢失其他元素(如测试颜色和边框等)的不透明度。

    background-color: rgba(71,158,0,0.8);
    

    使用不透明度的背景色

    背景色:rgba(r,g,b,不透明度);

    enter image description here

        28
  •  -2
  •   Vijay Sharma    8 年前

    您可以在RGB(63245,0)中使用不透明度类似于此颜色代码的RGB颜色,并添加不透明度类似于(63245,0,0.5),还可以添加RGB替换RGB。不透明度的使用

    div{
      background:rgba(63,245,0,0.5);
      }