首页 文章

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

提问于
浏览
2066

是否可以,仅使用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 .

27 回答

  • 13

    background-color:rgba(255,0,0,0.5); 如上所述是最简单的答案 . 要说使用CSS3,即使在2013年,也不简单,因为各种浏览器的支持程度随着每次迭代而变化 .

    虽然所有主流浏览器都支持 background-color (不是CSS3的新手)[1]但是alpha透明度可能很棘手,特别是对于版本9之前的Internet Explorer以及版本5.1之前的Safari上的边框颜色 . [2]

    使用像CompassSASS这样的东西可以真正帮助 生产环境 和跨平台兼容 .


    [1] W3Schools: CSS background-color Property

    [2] Norman's Blog: Browser Support Checklist CSS3 (October 2012)

  • 2161

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

    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及更高版本 .

  • 461

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

    我们需要做的是加入CSS工作组讨论并让它们给我们一个background-opacity属性!它应该与多背景功能携手合作 .

  • 55

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

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

    • 一个(“后面”)符合窗格元素的大小而不影响内容的流动,

    • 和一个(“cont”)包含内容并帮助确定窗格的大小 .

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

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

    此外,它为您提供了很多自由背景;你可以自由地在后面的元素中添加任何东西,并且它不会影响内容的流动(如果你想要多个全尺寸的子图层,只要确保它们也有位置:绝对,宽度/高度: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和表达式,IIRC,并且上次我检查时,第二个CSS变体在Opera中不起作用 .

    需要注意的事项:

    • 不包含cont图层内的浮动元素 . 你'll need to make sure they are cleared or otherwise contained, or they' ll从底部滑出来 .

    • 边距位于窗格元素上,填充位于cont元素上 . Don 't do use the opposite (margins on the cont or padding on the pane) or you'll会发现奇怪的事情,例如页面总是比浏览器窗口略宽 .

    • 如前所述,整个事情需要是块或内联块 . 随意使用 <div> 而不是 <span> 来简化您的CSS .


    一个更全面的演示,通过与 display: inline-block 一起使用,以及 auto 和特定的 width s / min-height 来展示这种技术的灵活性:

    .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.
    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.
    Pane content.
    Pane content.
    Pane content.
    Pane content.
    Pane content.
    Pane content.
    Pane content.
    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.
    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.
    Pane content. </span> </p>

    这是广泛使用的技术live demo

  • 15

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

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

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

  • 10

    CSS3可以轻松解决您的问题 . 使用:

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

    这里,rgba代表红色,绿色,蓝色和alpha值 . 由于255获得绿色值,并且通过0.5α值获得半透明度 .

  • 56

    在Firefox 3和Safari 3中,您可以像Georg Schölly mentioned一样使用RGBA .

    一个鲜为人知的技巧是您可以使用渐变过滤器在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

  • 21

    有一个更简单的解决方案,可以在同一个div上的图像上叠加 . 这不是正确使用这个工具 . 但就像使用CSS制作叠加层的魅力一样 .

    使用这样的插入阴影:

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

    就这样 :)

  • 7

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

    只需打开Photoshop,创建一个 2x2 像素图像(picking 1x1 can cause an Internet Explorer bug!),用绿色填充它并将"Layers tab"中的不透明度设置为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');
    }
    
  • 3

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

    在CSS中使用 :before (或 :after )并为它们提供不透明度值,以使元素保持其原始不透明度 . 因此,您可以使用: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 (使用零值或任何更适合您需要的值) .

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

    你可以使用css这样的rgba颜色代码,如下图所示 .

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

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

    所以,简单地做这样的事情就可以适用于你的情况:

    p {
      position: absolute;
      background-color: rgba(0, 255, 0, 0.6);
    }
    
    span {
      color: white;
    }
    
  • 7

    如果您使用Less,则可以使用 fade(color, 30%) .

  • 0

    您可以使用不透明度的RGB颜色,如RGB(63,245,0)中的此颜色代码,并添加不透明度(63,245,0,0.5),并添加RGBA替换RGB . 用于不透明度

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

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

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

    否则就不可能 .

    编辑:

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

  • 14

    这是我能想到的最佳解决方案,而不是使用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.
        
    Background should grow to fit. </div> <div class="background"></div> </div>
  • 12

    这是一个jQuery插件,它将为您处理一切,Transify(Transify - a jQuery plugin to easily apply transparency / opacity to an element’s background) .

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

  • 10

    这是我如何做到这一点(它可能不是最佳的,但它的工作原理):

    创建您想要半透明的 div . 给它一个类/ id . 保持EMPTY,然后关闭它 . 给它一个设定的高度和宽度(比如300像素乘300像素) . 给它一个0.5的不透明度或任何你喜欢的颜色和背景颜色 .

    然后,直接在该div下面,创建另一个具有不同类/ id的div . 在其中创建一个段落,您可以在其中放置文本 . 给 div 位置:relative和top: -295px (这是NEGATIVE 295像素) . 给它一个z-index为2以获得良好的度量,并确保其不透明度为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 .

  • 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**
    }
    
  • 6

    我通常用这个班来做我的工作 . 这是相当不错 .

    .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 */
    }
    
  • 4

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

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

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

    以外那,

    你可以使用 two side-by-side sibling elements 伪造它 - make one semi-transparent ,然后 absolutely position the other over the top

  • 4

    Opacity of background, but not the text有一些想法 . 要么使用半透明图像,要么覆盖其他元素 .

  • 1

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

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

    //值越小透明度越高,值越小透明度越低 .

  • 101

    前段时间,我在Cross Browser Background Transparency With CSS写了这篇文章 .

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

  • -2

    您可以使用渐变语法通过(ab)为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')";
    
  • 0

    您可以使用纯CSS 3rgba(red, green, blue, alpha) ,其中 alpha 是您想要的透明度级别 . 不需要JavaScript或jQuery .

    这是一个例子:

    #item-you-want-to-style{
        background:rgba(192.233, 33, 0.5)
    }
    

相关问题