shurup
shurup

Reputation: 871

Why does relative positioning remove opacity?

I made a simple site where there is an image in the background that has 0.3 opacity, and there is also a background color. On top of all that is some text. Here is the HTML:

If I make the position relative, the text is NOT affected by the opacity of the image. If I make don't make it relative, it is affected by the opacity. I am just wondering why relative positioning has such an effect.

.bg-1 {
  width: 100%;
  height: 80vh;
  background: url(img/keyboard.jpg) no-repeat center center;
  background-position: top;
  background-size: cover;
  opacity: .3;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

#welcome {
  padding-top: 15px;
  color: #66FCF1;
  z-index: 1;
  position: relative;
  /*this is the point of concern*/
}

.first {
  width: 100%;
  height: 80vh;
  background-color: black;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container-fluid first text-center">
  <div id="welcome">
    <p class="welcomeSize">Welcome!</p>
  </div>
  <div class="bg-1">
    <!--the bg image with opacity-->
  </div>
</div>

Upvotes: 1

Views: 1957

Answers (2)

haxxxton
haxxxton

Reputation: 6442

By default, elements are loaded in the order they are specified in your html. In this case, your .bg-1 element loads after (and hence, on top of) your #welcome element.

Similarly, z-index is only applied to positioned elements (ie. fixed, relative, and absolute). When you apply position:relative you are triggering the z-index to be applied, and "lifting" the #welcome element above your background image

Upvotes: 2

Michael Coker
Michael Coker

Reputation: 53709

What you're seeing is z-index. Even though you already have a z-index on #welcome, a z-index property doesn't take effect until you add a non-static position to the element with the z-index. So adding position: relative activates the z-index on #welcome, putting #welcome on top of .bg-1 instead of behind it.

Upvotes: 4

Related Questions