How do I give text or an image a transparent backg

2018-12-30 23:00发布

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

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:1 is relative to the opacity:0.6 of the parent.

标签: html css opacity
28条回答
君临天下
2楼-- · 2018-12-31 00:00

You can use RGBA (red, green, blue, alpha) in the CSS, something like this:

So simply do something like this gonna work in your case:

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

span {
  color: white;
}
查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 00:02

Either use a semi-transparent PNG image or use CSS3:

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

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

查看更多
步步皆殇っ
4楼-- · 2018-12-31 00:02

Here is a jQuery plugin that will handle everything for you, Transify (Transify - a jQuery plugin to easily apply transparency / opacity to an element’s background).

I was running into this problem every now and then, so I decided to write something that would make life a lot easier. The script is less than 2 KB and it only requires 1 line of code to get it to work, and it will also handle animating the opacity of the background if you like.

查看更多
有味是清欢
5楼-- · 2018-12-31 00:03

I normally use this class for my work. Its pretty good.

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

查看更多
登录 后发表回答