Set background image with opacity

2018-12-31 23:57发布

So, I can see in CSS references how to set image transparency and how to set a background image. But how can I combine these two in order to set a transparent background image?

I have an image that I'd like to use as a background, but it is too bright - I'd like to turn the opacity down to about 0.2. How can I do this?

#main {
    background-image: url(/wp-content/uploads/2010/11/tandem.jpg); 
}

标签: css
14条回答
十年一品温如言
2楼-- · 2019-01-01 00:35

You can use CSS psuedo selector ::after to achieve this. Here is a working demo.

enter image description here

.bg-container{
  width: 100%;
  height: 300px;
  border: 1px solid #000;
  position: relative;
}
.bg-container .content{
  position: absolute;
  z-index:999;
  text-align: center;
  width: 100%;
}
.bg-container::after{
  content: "";
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index:99;
  background-image: url(https://i.stack.imgur.com/Hp53k.jpg);
  background-size: cover;
  opacity: 0.4;
}
<div class="bg-container">
   <div class="content">
     <h1>Background Opacity 0.4</h1>
   </div>
</div>

查看更多
时光乱了年华
3楼-- · 2019-01-01 00:37

I have used the answer of @Dan Eastwell and it works very well. The code is similar to his code but with some additions.

.granddata {
    position: relative;
    margin-left :0.5%;
    margin-right :0.5%;
}
.granddata:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url("/Images/blabla.jpg");
    width: 100%;
    height: 100%;
    opacity: 0.2;
    z-index: -1;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment:fixed;
}
查看更多
明月照影归
4楼-- · 2019-01-01 00:42

Two methods:

  1. Convert to PNG and make the original image 0.2 opacity
  2. (Better method) have a <div> that is position: absolute; before #main and the same height as #main, then apply the background-image and opacity: 0.2; filter: alpha(opacity=20);.
查看更多
无色无味的生活
5楼-- · 2019-01-01 00:42

I had a similar issue and I just took the background image with photoshop and created a new .png with the opacity I needed. Problem solved without worrying about if my CSS worked accross all devices & browsers

查看更多
低头抚发
6楼-- · 2019-01-01 00:45

Well the only CSS way of doing only background transparency is via RGBa but since you want to use an image I would suggest using Photoshop or Gimp to make the image transparent and then using it as the background.

查看更多
残风、尘缘若梦
7楼-- · 2019-01-01 00:46

In your CSS add...

 filter: opacity(50%);

In JavaScript use...

 element.style.filter='opacity(50%)';

NB: Add vendor prefixes as required but Chromium should be fine without.

查看更多
登录 后发表回答