如何在css中使网页背景图片透明?

6
根据我的了解,没有CSS属性可以使背景图像透明, 我一遍又一遍地尝试,但仍然离解决方案很远, 以下是我的方法:
body {
    background-image: url("PPI01.jpg");
    background-attachment: fixed;
    background-position: bottom;
    filter: opacity(opacity: 30%);
    z-index: -1;
    background-repeat: no-repeat;
}

我查看了其他类似的问题,发现有相似的情况,但问题仍然存在。
5个回答

15
将你的背景放到body::after

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
body {
  width: 1200px;
  height: 1200px;
  display: block;
  position: relative;
  margin: 0 auto;
  z-index: 0;
}

body::after {
  background: url(http://kingofwallpapers.com/background-image-laptop/background-image-laptop-018.jpg);
  content: "";
  opacity: 0.9;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: -1;   
}

div {
  font-size: 36px;
  color: white;
}

    </style>
</head>
<body>
 <div>
   The text will not affected by the body
 </div>
</body>
</html>


我明白了,伙计,谢谢你的帮助。看起来你给出了解决我问题最简单的方法。 - user7534422

0
我分享我的答案,因为我认为它比被接受的解决方案更好,主要是因为我的解决方案可以在HTML中设置图像URL,正如我所需。您还可以轻松地为不同的不透明度级别制作不同的CSS类:)
CSS:
body.light-bg {
  background-position-x: 50% !important;
  background-position-y: 50% !important;
  background-size: cover !important;
}
body.light-bg::before {
  background: white;
  content: "";
  height: 100%;
  opacity: 0.35;
  position: absolute;
  width: 100%;
  z-index: -1;
}

HTML:

<body style="background: url(image.png)" class="light-bg"></body>

0

另一种方法是使用绝对定位图像作为背景,并使用以下属性设置图像:

img {
    opacity: 0.5;
    filter: alpha(opacity=50); /* For IE8 and earlier */
}

在样式表中使用图像源URL使得动态更改源变得困难。

通常,背景图像是预处理的,您还可以考虑将其首先制作为透明的PNG文件,然后将其上传到静态服务器中,这样您就可以使用像PS、Sketch这样的图像处理应用程序使图像透明。


-1

你可以使用rgba背景属性,搭配白色和透明度。

background; rgba(255, 255, 255, 0.3) url(IMAGE_PATH); /* Add other attributes as required */

-1

您应该使用 opacity 属性来设置值。允许的值范围是从 0 到 1。

body {
    background-image: url("PPI01.jpg");
    background-attachment: fixed;
    background-position: bottom;
    opacity: 0.3;
    z-index: -1;
    background-repeat: no-repeat;
}

请查看W3C上完整的文档


1
请注意,以下是关于编程的内容。只返回翻译后的文本:请注意,内容将受到不透明度的影响。 - Adam Wolski
同意。我的错。刚刚意识到。 - NutcaseDeveloper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接