Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS overlapping elements & opacity issue

Tags:

css

I've stumbled upon an issue with rendering two overlapping elements with opacity = .5. The elements are exactly the same and positioned absolutely. One is on top of the other. Common sense tells that the effect should give us an image with 100% opacity (0.5+0.5 = 1), but it doesn't.

I would really appreciate if anyone cared to explain the mechanism of rendering such elements, because clearly there's some underlying issue that I don't get.

HTML:

<div class="test">
    <img src="..." alt="" width="200" height="200" class="t"/>
    <img src="..." alt="" width="200" height="200" class="t"/>   
</div>
<img src="..." alt="" width="200" height="200" class="test"/> 

CSS:

.test{
    float: left;
    position:relative;
    width: 200px;
    height: 200px;
}
.test .t{
    position:absolute;
    top:0;
    left:0;
    opacity: 0.5;
}


jsFiddle

Thanks

like image 699
mpietrowiak Avatar asked Jan 22 '14 22:01

mpietrowiak


People also ask

Can elements overlap in CSS?

We can use CSS absolute positioning to overlap elements, but there's some advantages to using CSS grid instead. Let's explore using CSS grid as an alternative to position absolute.

Why are my CSS elements overlapping?

Elements can overlap for a variety of reasons, for instance, relative positioning has nudged it over something else. Negative margin has pulled the element over another. Absolutely positioned elements overlap each other.

What are overlapping elements?

Using CSS Z-Index property developer can stack elements onto one another. Z-Index can have a positive or a negative value. NOTE − If elements that overlap do not have z-index specified then that element will show up that is mentioned last in document.


2 Answers

Try and think of it like percentage sales. It's a bit different, but the analogy gives sense of what's happening. When a $10 item is 80% off, then you take off an additional 20%, it's' not 100% off (80% + 20%). You calculate final price like this:

$10 * (1 - 0.8)  = $2 * (1 - 0.2) = $1.60.

50% opacity means, 50% of the light is blocked. So when you stack two 50% opacity elements, that means 50% of the light is blocked and 50% more light is blocked by the additional layer. Since only 50% light is coming through the first layer, only 50% of that additional light is blocked. So the calculation would be:

50% + (50% * 50%) = 75% opacity.

DEMO

.num2 {
    opacity: 0.75;
}
like image 99
brouxhaha Avatar answered Sep 20 '22 11:09

brouxhaha


There are three items being added together:

  • White background at 100%
  • First picture at 50%
  • Second picture at 50%

The first two make the first picture much lighter prior to mixing with the second picture.

like image 35
Don Rhummy Avatar answered Sep 20 '22 11:09

Don Rhummy