如何使用CSS为背景图像着色?

use*_*053 33 css background tint

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

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

我计划为网站的不同页面提供不同的背景图像:因此,文本在其上清晰可读非常重要.现在,我在中间的#main内容框中有一个半透明的黑色背景,以确保易读性:

#main {
background: rgba(0, 0, 0, 0.5);
}
Run Code Online (Sandbox Code Playgroud)

然而,我真正想做的是在整个背景图像上都有这种半透明的背景,因为黑盒看起来有点笨重.我已经尝试制作一个<div id=#tint>包含整个HTML文档并给予#tint的rgba(0,0,0,0.5),但这根本不起作用 - 我可以得到任何改变或者我可以得到整个背景变成一个简单的灰色,根本没有可见的背景图像.这根本不可能吗?

hit*_*uct 69

background-blend-mode一个简单的色调

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

.background-tint {
  background-color: rgba(200,100,0,.5); // Tint color
  background-blend-mode: multiply;
}
Run Code Online (Sandbox Code Playgroud)

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

该属性在现代浏览器中得到很好的支持,包括IE最新版和Edge版(可以使用标记启用预览状态).对于非支持的浏览器,您可以使用polyfill.

工作演示


其他选择

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

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

我认为这是最广泛使用的技术,但它有硬编码的缺点,即你不能只是拿一个类,坚持一个元素并做一个色调.

你可以把它变成一个更少或更少的混合,例如:

filter

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

filter

.background-tint(@tint-color, @image-url) {
  background-image: 
    linear-gradient( @tint-color, @tint-color ),
    url( @image-url )
}
Run Code Online (Sandbox Code Playgroud)

工作演示

使用透明背景

@mixin background-tint($tint_color, $image_url) {
  background-image: 
    linear-gradient( $tint_color, $tint_color ),
    url( $image_url )
}
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是可以在大多数浏览器上运行,只是添加到任何元素的一个很好的类.缺点是,如果你在该元素中有任何其他东西,你将不得不将它包装在一个div中,某种定位hue-rotate最好.

例:

.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);
}
Run Code Online (Sandbox Code Playgroud)
<div class="background-tint">
  <div class="u-relative">Some text here</div>
</div>
Run Code Online (Sandbox Code Playgroud)

工作演示

  • 这应该是接受的答案+1 (4认同)

Chr*_*ris 19

我认为你需要创建一个覆盖元素(可能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*/
}
Run Code Online (Sandbox Code Playgroud)

当然还有一点点演示:小链接.


Chr*_*ini 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);
}
Run Code Online (Sandbox Code Playgroud)

并以另一个答案为基础,您可以使用现有颜色执行此操作,而不是:

linear-gradient(
  fade(@brand-primary, 50%),
  fade(@brand-primary, 50%)
),
Run Code Online (Sandbox Code Playgroud)