norixxx
norixxx

Reputation: 3189

CSS stack order changes when parent content has image as child, and also other element has opacity

I found strange behavior when coding css specifically using negative margin to stack element on other element.

I understand natural stack order that when elements overlap, later element always goes on top(not using relative, absolute positioning).

Question1: Why If former element has image element, later element go under the image?

Question2: Moreover, when later element has opacity other than 1, later element go over the former element (set back to natural order?)

HTML:

<div class="box sample1">
        <img src="http://fillmurray.com/100/100" alt="">
</div>
<div class="box sample1-2">opacity: 1</div>


<div class="box sample1-3">
    <img src="http://fillmurray.com/100/100" alt="">
</div>
<div class="box sample1-4">opacity: .9</div>

SCSS:

.box {
    width: 100px;
    height: 100px;
}
.child {
    width: 80px;
    height: 80px;
}
.sample1 {
    background-color: yellow;
    width: 300px !important;
}
.sample1-2 {
    background-color: red;
    margin-top: -40px;

    .child {
        // background-color: green;
    }
}

.sample1-3 {
    // opacity: .9;
    width: 300px;
    background-color: green;
}
.sample1-4 {
    opacity: .9; //this changes stack order
    background-color: red;
    margin-top: -40px;
}

Demo: https://jsfiddle.net/nori2tae/4w62t746/8/

Need a little explanation to this, thanks.

Upvotes: 1

Views: 260

Answers (1)

Danield
Danield

Reputation: 125531

Question1: Why If former element has image element, later element go under the image?

It's because within the same stacking context - inline-level elements (such as the image) are painted above non-inline-level elements (see this post)

This article has a nice image to sum up the stacking order of elements within the same stacking context:

enter image description here

Question2: Moreover, when later element has opacity other than 1, later element go over the former element (set back to natural order?)

It's because a new stacking context is formed on an element with a opacity value less than 1.

From the spec: (bold mine)

If an element with opacity less than 1 is positioned, the ‘z-index’ property applies as described in [CSS21], except that ‘auto’ is treated as ‘0’ since a new stacking context is always created.

See all this MDN article on stacking contexts.

Upvotes: 1

Related Questions