Daniel
Daniel

Reputation: 21

Background image with opacity

I've been trying to display a navigation bar in front of a full screen size background image which I want to adjust it's opacity. I am able to display the nav bar and the image correctly until I modify the image's opacity. When I do that, the background image is not displayed full size. The image is only displayed until the navigation bar starts

html {
    background-image:url(../img/sea.jpg);
    background-size: 100%;
    opacity: 0.5;
}
.navigation {
        background-color: grey;
        list-style: none;
        padding-left: 0;
        position: fixed;
        text-align: center;
        top:300px;
        width: 100%;

}

.navigation li{
    display: inline-block;
    height:20px;
    width:110px;
}

.navigation a{
    text-decoration: none;
}

Upvotes: 1

Views: 3654

Answers (1)

thomasstephn
thomasstephn

Reputation: 3835

Opacity applies to your entire element, not only your background. So by doing

html {
    background-image:url(../img/sea.jpg);
    background-size: 100%;
    opacity: 0.5;
}

You are telling your entire document (html) to have a 50% opacity.

So if you're trying to have a background with opacity of 50% two options:

option 1

Your background is fixed and will only be 50% opacity, all the time: I recommend to modify the image itself to be a 50% opacity image (via any image editor) and save it as png which will preserve opacity. This however is good only if 2 conditions are matched:

  1. Your background opacity will never change
  2. Your image is fairly small ( a png is significantly bigger than a jpg for example, and so if you want your page load to be reasonnable, keep it small using a repeatable image for example).

option 2 (what you want I think)

Your background opacity needs to change for any reason, or is too big in png and you want to keep it as a jpg or whatever your format is: add a div containing your background and only your background, and change its opacity like below.

html {
  min-height: 100%; /* or whatever your desired height is */
  height: 100%; /* or whatever your desired height is */
  min-width: 100%; /* or whatever your desired width is */
  width: 100%; /* or whatever your desired width is */
}

#background {
  background-image:url(../img/sea.jpg);
  background-size: 100%;
  opacity: 0.5;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 0; /* To make sur it's below the rest */
}

And your html should be something like that:

 <html>
   <div id="background"></div>
   ... All your other html goes here ...
 </html>

Upvotes: 1

Related Questions