How can I display a header element above my content?

无人久伴 提交于 2019-12-11 17:34:37

问题


How can I display all headers above the content divs? ('above' on the z-axis) so that the visible z-order is:

  1. CONTENT 1 (bottom-most element)
  2. CONTENT 2
  3. HEADER 1
  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!