Using Opacity To Change The Stacking Order
can anyone explain why does opacity have any affect on stacking of html element ? Relevant part of the CSS Code: div:first-child{ opacity: 0.99; } .red{
Solution 1:
UPGRADE
See Snippet 2
- In order for
z-index
to be of any use, the element has to to have one of the following:
position:absolute
position:relative
position:fixed
opacity
works on a scale of 0 to 1, so having a .99 is useless.
<span>
sinline
elements and don't start with any discernable width or height, so in order to actually see any background, you need to give them some dimensions (i.e. height and width) or content (i.e. text inside of them). It also helps if you assigndisplay:inline-block
because dealing withdisplay:inline
isn't intuitive.
In Snippet 1 I've added the what was previously mentioned in your code.
In Snippet 2 I have made an interactive demo showing z-index
and opacity
stacking relationship.
SNIPPET 1
div:first-child {
opacity: 0.2;
}
.red {
position: relative;
background: red;
z-index: 1;
}
.green {
position: relative;
background: green;
margin: 20px0020px;
}
.blue {
position: relative;
background: blue;
margin: 40px0040px;
}
span {
display: inline-block;
width: 100px;
height: 20px;
}
<div><spanclass="red"></span></div><div><spanclass="green"></span></div><div><spanclass="blue"></span></div>
SNIPPET 2
document.getElementById('rng1').oninput = function() {
var rad = document.querySelectorAll('.rad:checked')[0];
var out = rad.nextElementSibling.id;
document.getElementById(rad.value).style.opacity = this.value;
document.getElementById(out).value = this.value;
}
#parent {
position: relative;
width: 480px;
height: 200px;
border: 3px dashed grey;
background: rgba(0, 0, 0, .2);
text-align: right;
}
fieldset {
width: 450px;
}
div {
position: absolute;
width: 300px;
height: 150px;
}
#A {
background: tomato;
z-index: 10;
text-align: left;
}
#B {
background: cyan;
z-index: 0;
text-align: center;
}
#C {
background: yellow;
z-index: -10;
text-align: right;
}
output {
width: 30px;
display: inline-block;
}
<sectionid='parent'><divid='A'>A</div><divid='B'>B</div><divid='C'>C</div>
Parent
</section><formid='ui'><fieldset><label><inputid='radA'class='rad'name='rad'type='radio'value='A'checked>A:
<outputid='oA'></output></label><label><inputid='radB'class='rad'name='rad'type='radio'value='B'>B:
<outputid='oB'></output></label><label><inputid='radC'class='rad'name='rad'type='radio'value='C'>C:
<outputid='oC'></output></label><label><inputid='radD'class='rad'name='rad'type='radio'value='parent'>Parent:
<outputid='oD'></output></label><br><label>Opacity
<inputid='rng1'type='range'min='0'max='1'step='.1'value='1'></label></fieldset></form>
Post a Comment for "Using Opacity To Change The Stacking Order"