问题
How can I display all headers above the content divs? ('above' on the z-axis) so that the visible z-order is:
- CONTENT 1 (bottom-most element)
- CONTENT 2
- HEADER 1
- HEADER 2 (top-most element)
I cannot change the DOM structure much: each header and div must be grouped in an article.
Also, there will be an unknown number of these articles, not just two.
article {
position: fixed;
opacity: .75;
}
article.one {
transform: translateY(20px);
color: blue;
}
article.two {
transform: translateX(100px);
color: red;
}
header {
position: fixed;
width: 280px;
height: 100px;
margin: 10px;
background-color: currentColor;
}
div {
background-color: black;
height: 600px;
width: 300px;
}
span { color: white; }
<article class="one">
<header><span>HEADER 1</span></header>
<div><span>CONTENT 1</span></div>
</article>
<article class="two">
<header><span>HEADER 2</span></header>
<div><span>CONTENT 2</span></div>
</article>
回答1:
This is impossible. The article elements are position: fixed
so they establish their own stacking contexts.
You can only position the header and div within the three-dimensional box established by the article.
This means you cannot have the content of one article between different parts of the content of another.
回答2:
The only way to achieve this is to be sure all your elements belong to the same stacking context so you need to avoid all the properties that creates stacking context like transfrom, opacity, fixed position, etc on the article elements:
article.one header {
background: blue;
color:#fff;
}
article.two header {
background: red;
color:#fff;
width:200px;
}
article.two {
margin-top:-115px;
}
header {
width: 280px;
height: 20px;
margin:5px 10px;
position:relative;
z-index:1;
}
article div {
position:relative;
z-index:-1;
background:green;
height:100px;
margin-top:-8px;
color:#fff;
}
article.two div {
background:pink;
}
<article class="one">
<header><span>HEADER 1</span></header>
<div><span>CONTENT 1</span></div>
</article>
<article class="two">
<header><span>HEADER 2</span></header>
<div><span>CONTENT 2</span></div>
</article>
来源:https://stackoverflow.com/questions/51769675/how-can-i-display-a-header-element-above-my-content