简体   繁体   中英

How do I make a background image transparent in CSS?

<style>
  header {
   text-align: center;
   background-image: url('http://i.imgur.com/7L79iny.jpg');
   background-size: 100% 100%;
   background-repeat: no-repeat;  
  }

This is the code I'm using to add a background image to my header. How to I make the image semi-transparent without making the rest of the header transparent.

<header>
 <center><a href="http://imgur.com/EPd7PBU"><img src="http://i.imgur.com/EPd7PBU.jpg" height=350 title="source: imgur.com" /></a></center>
 <h1>Taylor's Blog</h1>
 <ul>
 <li><a href="#">About Me</a></li>
 <li><a href="#">Blogs</a></li>
 <li><a href="#">Contact Me</a></li>
 </ul>
</header>

You cannot change the opacity of a background image with css, only the opacity of an element. However, there is a very easy work-around, that only requires css:

 header { text-align: center; position:relative; } header:after{ content:''; position:absolute; z-index:-1; top:0; bottom:0; left:0; right:0; background-image: url('http://i.imgur.com/7L79iny.jpg'); background-size: 100% 100%; background-repeat: no-repeat; opacity:0.5; } 
 <header> <a href="http://imgur.com/EPd7PBU"><img src="http://i.imgur.com/EPd7PBU.jpg" height=350 title="source: imgur.com" /></a> <h1>Taylor's Blog</h1> <ul> <li><a href="#">About Me</a></li> <li><a href="#">Blogs</a></li> <li><a href="#">Contact Me</a></li> </ul> </header> 

On another note, <center> is depreciated , and should not be used. In fact, in the case of the html you have, the link and image are already centered with text-align:center; , making the center tag useless.

The best way would be to create an absolutely positioned div that is transparent and is layered under the content.

<style>
  header {
   position: relative;
  }
  header .background {
   position: absolute;
   width: 100%;
   height:100;
   opacity: .5;
   background-image: url('http://i.imgur.com/7L79iny.jpg');
   background-size: 100% 100%;
   background-repeat: no-repeat;  
  }
</style>

sadsad

<header>
 <div class="background"></div>
 <center><a href="http://imgur.com/EPd7PBU"><img src="http://i.imgur.com/EPd7PBU.jpg" height=350 title="source: imgur.com" /></a></center>
 <h1>Taylor's Blog</h1>
 <ul>
 <li><a href="#">About Me</a></li>
 <li><a href="#">Blogs</a></li>
 <li><a href="#">Contact Me</a></li>
 </ul>
</header>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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