Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS z-index has no effect on the label for an input element

Tags:

css

label

z-index

I'd like to use the checkbox hack to expand a div to show more text. The hack requires the checkbox input to appear first in the DOM, with the elements that it is to affect coming after. I'd like to show the div that is to be expanded behind the label. I had imagined that it would be enough to set the z-index of the label so that it appears above the div:

HTML

<input type="checkbox" id="more" />
<label for="more">Show more</label>
<div>
    <p>Ipsum lorem and all that jazz</p>
</div>

CSS

input {
    position:absolute;
    clip: rect(0, 0, 0, 0);
    z-index: 999;
}
input + label {
    z-index: 999;
}
input + label::before {
    content:"+";
    padding-right: 0.5em;
    font-family: monospace
}
input:checked + label::before {
    content:"-";
}
input ~ div {
    height: 0;
    padding-top: 1em;
    background: #ffe;
    overflow:hidden;
    position: relative;
    top: -0.4em;
}
input:checked ~ div {
    height: auto;
}

However, no value of z-index seems to have any effect. I understand that there may be different stacking contexts in an HTML page. However, I don't see how this affects my simple layout. Removing the position: absolute rule for the input element does not remove the problem, nor does changing the z-index of the input element itself.

What wrong assumptions I am making?

jsfiddle


EDIT: Thanks to @Guy and @taxicala, I've got the demo working: here's an updated jsfiddle

like image 987
James Newton Avatar asked Jan 08 '23 03:01

James Newton


2 Answers

z-index is intended for elements positioned as absolute, relative and fixed:

input + label {
    position: relative;
    z-index: 999;
}
like image 118
taxicala Avatar answered Mar 30 '23 00:03

taxicala


Currently your label is position: static, change it to position: relative for the z-index to be applied.

Updated Fiddle

like image 35
Guy Avatar answered Mar 29 '23 22:03

Guy