Search code examples
htmlcssz-index

z-index doesn't work correctly when using article elements


Basically I want to show <article id="characters"> on top of <article id="accordion">. But as you can see, the characters-article is not on top or even behind the accordion-article. It's put below the article.

What am I doing wrong?

#appchap {
  display: block;
  position: relative;
  z-index: 100;
  overflow-x: hidden;
  overflow-y: auto;
}

article#accordion {
  display: block;
  position: relative;
  z-index: -1;
}

article#accordion section {
  display: block;
  position: relative;
  height: 25px;
  background-color: blue;
  z-index: -1;
}

article#characters {
  display: block;
  position: relative;
  z-index: 1;
}

article#characters section {
  display: block;
  position: relative;
  height: 25px;
  z-index: 1;
  background-color: red;
}
<div id="appchap">
  <article id="accordion">
    <section>number 1</section>
    <section>number 2</section>
  </article>
  <article id="characters">
    <section>Main characters</section>
  </article>
</div>


Solution

  • If two block elements are siblings in the DOM, then all else being equal — and in this case all else is equal — they will be rendered one followed by the other.

    If that wasn't the case, then something as simple as <p>Hello</p><p>World</p> would end up with the text overlapping.

    If you want them to overlap then you need to do something explicit to make them overlap such as:

    • absolutely positioning them and giving them the same top value or
    • Giving the second element a negative margin-top