skip to Main Content
body {
  background: url(bg.jpg);
  margin: 0;
}

#bg {
  background-color: black;
  margin: 0;
  padding: 0;
  height: 100vh;
  opacity: 0.7;
}

#topbar {
  background-color: gray;
  height: 80px;
  width: 100%;
}
<div id="bg">
  <div id="topbar"></div>
</div>

I’ve tried adding opacity: 1 to the topbar div and rgba with alpha: 1.
The result: there`s an image, black background over it with opacity 0.7 and topbar which also has opacity 0.7.

My goal is to achieve darker image as a background and solid color topbar div.

2

Answers


  1. #topbar is inside of #bg, so adjusting the opacity of #bg also affects #topbar. What I would do instead is omit opacity and change the background color to a transparent black.

    That would look like this:

    body {
        background: url(bg.jpg);
        margin: 0;
    }
    
    #bg {
        background-color: rgba(0, 0, 0, 0.7);
        margin: 0;
        padding: 0;
        height: 100vh;
    }
    
    #topbar {
        background-color: gray;
        height: 80px;
        width: 100%;
    }
    

    This way only the background color is transparent instead of the entire element.

    Login or Signup to reply.
  2. The answer by @CoffeedUpHacker is good, but here is an alternative which has some extra benefits.

    Here I do not nest #topbar inside #bg; they are siblings. I then style #bg with the background-image rather than body. This has the following benefits:

    1. You can use a filter to reduce the brightness instead of a partially-transparent black overlay (one element instead of two).
    2. You can have the background fixed and it will work on all devices (whereas using background-attachment: fixed on the body element is not currently supported on mobile devices).
    body {
      margin: 1em;
      color: white;
    }
    
    #bg {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: -1;
      background: url(http://picsum.photos/id/85/1500/1000);
      background-size: cover;
      background-position: center;
      filter: brightness(30%);
    }
    
    #topbar {
      margin: -1em -1em 1em -1em;
      padding: 1em;
      background-color: gray;
      height: 4em;
    }
    <div id="bg"></div>
    <div id="topbar">top bar</div>
    page text
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search