The most famous CSS property in HTML that determines the overlay order of elements is probably z-index. However, we often find that some situations are not consistent with our expectations during the project. After research and study, I finally figured out the relationship. A brief summary is as follows:
- Only the z-index attribute of Positioned (Position is not static) elements is valid
- z-index can be a negative number
- None Elements with z-index or invalid z-index (see Article 1) are equivalent to z-index of 0;
- elements that meet certain conditions, the browser will create something called stacking context for them . According to the DOM tree structure, stacking context will also form a tree structure.
- Elements in a stacking context will be stacked in order based on z-index. The one with the larger z-index comes first
- Among the z-index level 0 elements, the stacking order of elements with stacking context comes first
- When the above conditions cannot be distinguished, the order in the DOM tree is used to determine Overlay sequence.
There are a lot of details, and I’m not sure my understanding is correct. Any corrections are welcome.
In addition, below is a series of related articles from MDN. It is unfolded layer by layer and written very clearly. Students who are doing WEB can learn from it.
Stacking without z-index : Default stacking rules Stacking and float : How floating elements are handled Adding z-index : Using z-index to change default stacking The stacking context : Notes on the stacking context Stacking context example 1 : 2-level HTML hierarchy, z-index on the last level Stacking context example 2 : 2 -level HTML hierarchy, z-index on all levels Stacking context example 3 : 3-level HTML hierarchy, z-index on the second level