53

我有一个通过 CSS 设置的背景图像。

html {
background-image: url('../img/cello.jpg');
background-attachment: fixed;
background-size: 100%;
}

我计划为网站的不同页面设置不同的背景图像:因此文本清晰易读很重要。现在,为了确保易读性,我在中间的#main 内容框有一个半透明的黑色背景:

#main {
background: rgba(0, 0, 0, 0.5);
}

不过,我真正想做的是在整个背景图像上使用那种半透明的背景,因为黑盒子看起来有点笨重。我尝试制作一个<div id=#tint>包含整个 HTML 文档并将 rgba(0, 0, 0, 0.5) 给#tint,但这根本不起作用——我要么什么都没有改变,要么我可以得到整个背景变成一个简单的灰色,根本看不到背景图像。这根本不可能吗?

4

5 回答 5

114

用于background-blend-mode简单的色调

您可以使用background-blend-modecss 属性:

.background-tint {
  background-color: rgba(200,100,0,.5); /* Tint color */
  background-blend-mode: multiply;
}

将它放在任何带有背景图像的元素上,你就可以开始了。

该属性在包括 IE 11 的现代浏览器中得到很好的支持。对于不支持的浏览器,您可以使用polyfill

工作演示


其他选项

用于filter复杂的色调

您可以使用filtercss 属性:

.background-tint {
  filter: sepia(100%) saturate(200%) brightness(70%) hue-rotate(330deg);
}

将它放在任何带有背景图像的元素上,你就可以开始了。为了改变颜色改变hue-rotate值。

该属性在包括 IE 11 的现代浏览器中得到很好的支持。

工作演示

使用平面线性渐变和多背景叠加

.background-tint {
  background-image: 
    linear-gradient( rgba(0,0,0,.5), rgba(0,0,0,.5) ),
    url('http://placehold.it/420')
}

我认为这是最广泛使用的技术,但它具有硬编码的缺点,即您不能只上课,将其粘贴在元素上并进行着色。

你可以把它变成一个 less 或 sass mixin,比如:

less

.background-tint(@tint-color, @image-url) {
  background-image: 
    linear-gradient( @tint-color, @tint-color ),
    url( @image-url )
}

sass

@mixin background-tint($tint_color, $image_url) {
  background-image: 
    linear-gradient( $tint_color, $tint_color ),
    url( $image_url )
}

工作演示

使用透明背景

.background-tint { position: relative; }

.background-tint::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,.5);
}

此方法具有适用于大多数浏览器的优点,并且只是您添加到任何元素的一个不错的类。不利的一面是,如果您在该元素中还有其他任何内容,则必须将其包装在具有某种定位的 div 中position: relative效果最好。

例子:

<div class="background-tint">
  <div class="u-relative">Some text here</div>
</div>
.u-relative { position: relative; }

工作演示

于 2016-02-03T12:40:55.107 回答
24

我认为您需要创建一个div具有所需半透明背景的叠加元素(可能)。就像是:

.overlay {
    z-index: 1;
    height: 100%;
    width: 100%;
    position: fixed;
    overflow: auto;
    top: 0px;
    left: 0px;
    background: rgba(0, 0, 0, 0.7); /*can be anything, of course*/
}

当然,还有一个小演示:little link

于 2012-08-24T16:32:01.693 回答
7

这对我很有用:

https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {
  background: 
    /* top, transparent red, faked with gradient */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(image.jpg);
}

在另一个答案的基础上,你可以用现有的颜色来做到这一点,而不是像:

linear-gradient(
  fade(@brand-primary, 50%),
  fade(@brand-primary, 50%)
),
于 2015-09-21T19:33:26.930 回答
1

这将是overlay属性 https://dvcs.w3.org/hg/FXTF/rawfile/tip/compositing/index.html#blendingoverlay 但这是一个草稿。不要依赖它

于 2012-08-24T16:19:18.360 回答
0

试试不透明度:

opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
于 2012-08-24T16:00:02.190 回答