简体   繁体   English

使用媒体查询在背景图像上设置不透明度

[英]Set opacity on background-image with media query

I have a couple of divs, each with a background image. 我有几个div,每个div都有背景图片。 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...). 我使用的是自适应CSS,当我的div的宽度小于特定大小(760px btw)时,文本和某些带有样式的表格将变得难以阅读/看到,而背景图像则在它们后面移动(背景图片位于文字/表格的最右边,如果宽度大于 760px ...,则不会太明显。 So when the width of the viewport gets to 760px and less, I only want the background image to have an opacity... 因此,当视口的宽度小于等于760px时,我只希望背景图像具有不透明度...

How do I do that? 我怎么做?

So my CSS starts like this: 所以我的CSS像这样开始:

@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() : 您只能使用rgba()改变BG颜色的不透明度:

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). 您可以设置背景色的不透明度(有关示例,请参见Zoltan的回答 )。


You can set white <div> over the image and change it's opacity. 您可以在图像上设置白色<div>并更改其不透明度。

<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 现场演示: Tinkerbin


However, this won't work if you don't have a clean background BEHIND your image. 但是,如果您没有干净的背景隐藏图像,则此方法将无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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