如果我有以下代码,如何在CSS中使我的背景图像透明?

时间:2013-01-22 19:06:23

标签: html css background-image transparent

我试图让我的背景图像略微透明。我在这里阅读了另一篇关于这个主题的文章,但是当我尝试它时它没有用。我希望我没有给出太少或太多的信息。 这是我的HTML代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My Title</title>
<link type="text/css" rel="stylesheet" href="../Stylesheets/stylesheet1.css">
<link type="text/css" rel="stylesheet" href="../Stylesheets/stylesheet2.css">
<link type="text/css" rel="stylesheet" href="../Stylesheets/stylesheet3.css">
</head>

<body>
<div id="container">
    <div id="background" class="translucent"></div>
<div id="content">
    <div id="backgroundIMG">
</div>
</div>

<H1><div align="center">A heading</div></H1>
<p>
<div style="width:890px;height:40px;border:5px dotted Coral;">
CONTENT
</div>

<p>
CONTENT

<div class="index">
<H2>Index</H2>
Home (on now)
<br>
<a href="page2.html">Bored Main Page</a>
<br>
<a href="page3.html">Tables are here!</a>
</div>
</div>

</body>

以下是我的样式表:

stylesheet1:

html
{
    font-weight: bold;
}

body
{
margin-left:30px;
margin-right: 30px;
background-repeat: no-repeat;
width: 100%;
height: 100%;
}

stylesheet2:

.index
{
line-height: 1.5em;
padding: 1em;
border: DarkGreen solid 5px;
text-align: left;
width: 890px;
}

.bgCyan
{
background-color: cyan;
color: #525252;
}

.bgGreen
{
background-color: LightGreen;
color: DarkBlue;
}

.bgBoredText
{
background: url(../Images/my_image.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

.translucent
{
opacity: 0.4;
filter: alpha(opacity = 40); /* For IE */
}

stylesheet3:

#container
{
position: relative;
width: 200px;
height: 200px;
}

#background, #content
{
position: absolute;
top: 0;
left: 0;
}

#backgroundIMG
{
background-image: url(../Images/my_image.jpg);
}

提前谢谢

3 个答案:

答案 0 :(得分:2)

据我所知,CSS无法改变背景图像的不透明度 。您必须在图像编辑程序中更改图像以降低其不透明度。

答案 1 :(得分:1)

我有同样的问题,并从对另一个StackOverflow问题的回复中找到答案。诀窍是使用body元素的:after属性。 link

    body:after {
        content: "";
        background-image:url('http://www.w3schools.com/css/klematis.jpg');
        background-repeat:repeat;
        background-position:center;
        background-attachment:fixed;
        background-size:cover;
        opacity: 0.5;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        position: absolute;
        z-index: -1;
    }

答案 2 :(得分:0)

将此css添加到#backgroundIMG

 -khtml-opacity: 0.5; 
 -moz-opacity: 0.5; 
 -ms-filter:"alpha(opacity=50)";
  filter:alpha(opacity=50);
  opacity: 0.5;

请注意,使用不同的浏览器查看您的网页时会遇到一些困难。例如:IE8(及更早版本)不适用于opacity参数。