Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS

williamrossi
williamrossi
6,232 Points

Setting opacity in the background image

Hi guys, I was wondering if there was some css shorthand to alter the opacity in just the background image. here is what I have so far

background: $black url('/images/fashionpic.jpeg')no-repeat;

3 Answers

Andrew McCormick
Andrew McCormick
17,729 Points

position your div relative, and then set :after for your div absolute with a background image and an opacity.

<style type= "text/css">
#main {
   position: relative;
  height: 300px;
}
#main:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url(http://baseballwallpapers10.net/wp-content/uploads/images/7d/cleveland-indians-0.jpg); 
    width: 100%;
    height: 100%;
    opacity : 0.2;
    z-index: -1;
}
</style>

<body>
<div id="main">foo</div>
</body>

Live in CodePen

I did just reread your question and notice you asked specifically for a shorthand version. A shorthand version doesn't exists of yet for this.

David Wible
David Wible
7,473 Points

Instead of a bunch of extra code. The main method is to alter the background image in photo editor. :o) But Andrew's answer is correct as well, but I do seem to remember having to add, "filter: alpha(opacity=20);" as well to get it to work in certain browsers. Editing the photo makes it work no matter what. ;O

Chris James
Chris James
19,102 Points

Andrew this was really helpful top me, thanks!