CSS opacity only to background color not the text

2019-01-03 11:28发布

This question already has an answer here:

Can I assign the opacity property to the background property of a div only and not to the text on it?

I've tried:

background: #CCC;
opacity: 0.6;

but this doesn't change the opacity.

标签: css opacity
11条回答
等我变得足够好
2楼-- · 2019-01-03 12:01

This will work with every browser

div {
 -khtml-opacity:.50; 
 -moz-opacity:.50; 
 -ms-filter:”alpha(opacity=50)”;
  filter:alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
  opacity:.50; 
}

If you don't want transparency to affect the entire container and it's children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent to achieve this. http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/

Check working demo at http://www.impressivewebs.com/demo-files/css-opacity/css-opacity-demo.html

查看更多
成全新的幸福
3楼-- · 2019-01-03 12:03

I had the same problem. I want 100% Transparent background color, Just use this code, its worked great for me:

rgba(54, 25, 25, .00004);

You can see examples on the left side on this web page (the contact form area)

查看更多
做自己的国王
4楼-- · 2019-01-03 12:04

The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:

#container {
  position: relative;
  width: 300px;
  height: 200px;
}
#block {
  background: #CCC;
  filter: alpha(opacity=60);
  /* IE */
  -moz-opacity: 0.6;
  /* Mozilla */
  opacity: 0.6;
  /* CSS3 */
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}
#text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div id="container">
  <div id="block"></div>
  <div id="text">Test</div>
</div>

查看更多
太酷不给撩
5楼-- · 2019-01-03 12:05

The easiest solution is to create 3 divs. One that will contain the other 2, the one with transparent background and the one with content. Make the first div's position relative and set the one with transparent background to negative z-index, then adjust the position of the content to fit over the transparent background. This way you won't have issues with absolute positioning.

查看更多
Lonely孤独者°
6楼-- · 2019-01-03 12:07

My trick is to create a transparent .png with the color and use background:url().

查看更多
登录 后发表回答