简体   繁体   中英

Set opacity on background-image with media query

I have a couple of divs, each with a background image. I'm using responsive and adaptive CSS, and when my divs' widths gets less than a certain size(760px btw), the text and some tables with styling becomes hard to read/see with the background image moving in behind them(the background image is on the far right of the text/tables and unobtrusive if the width is above 760px...). So when the width of the viewport gets to 760px and less, I only want the background image to have an opacity...

How do I do that?

So my CSS starts like this:

@media screen and (max-width: 760px){
   background: #cdcdcd url("/images/back.jpg") no-repeat top right;
    /*How do I set the opacity of only the background?*/
} 

You can not change the opacity of a background image, unless you move it to a separate container.

All you can change is the opacity of BG color using rgba() :

background: rgba(0, 0, 0, .5);

You can't set opacity just for a background, but the whole element. You can set opacity of background color (see Zoltan's answer for the example).


You can set white <div> over the image and change it's opacity.

<div class="yourImage">
    <div class="imageCover"></div>
</div>
.yourImage {
  background: url(http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png);
  width: 300px;
  height: 83px;
}
.imageCover {
  background: #fff;
  width: 300px;
  height: 83px;
  opacity: .5;
}

Live demo: Tinkerbin


However, this won't work if you don't have a clean background BEHIND your image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM