An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
[CSS design] I think about specifying z-index difficult to break
Summary
Defines the z-index
value to be specified for each component.
Motivation
- I want to avoid
z-index
conflicts - Want to clarify the reason for specifying
z-index
- Don't want to increase
z-index
each time more components are added
Prerequisites
Rules for z-index
- Do not use
z-index
as much as possible. - Use
z-index
from0
to4
. - As a rule, do not use negative numbers such as
-1
.
Layer Stack rules
- Define the
z-index
value that a component should have on a layer (hierarchy) for each role. - Increase the
z-index
value as the layer stacks up.
Layer Stack 4 : z-index: 4
.
Element to be placed on top in any state.
- Modal
- Drawer
- Overlay
Layer Stack 3 : z-index: 3
Elements that are always placed on top.
An element that is always placed on top.
- Global header (e.g., fixed header to follow)
Layer Stack 2 : z-index: 2
.
- Tooltips
- Pop-overs
- Floating buttons (e.g., arrow buttons for carousels, etc.)
Layer Stack 1 : z-index: 1
.
Placed on top of an element that does not have a stack.
- Badge
Define z-index
.
:root { --layer-stack-1: 1; --layer-stack-2: 2; --layer-stack-3: 3; --layer-stack-4: 4;}.modal { z-index: var(--layer-stack-4);}.modal-in-modal { z-index: calc(var(--layer-stack-4) + 1);}
Rules for isolation
There may be a case where the z-index
conflicts between components in the Layer Stack definition alone, resulting in unintended overlapping. In such a case, you can solve the problem by using isolation
to generate stacking context in the root of the component.
.special-components { isolation: isolate; /* generate stacking context */ position: absolute;}.special-components__item { position: absolute; z-index: 100;}.modal { position: absolute; z-index: var(--layer-stack-4);}
Basically, it is preferable to use an HTML structure with no problems with just a z-index
specification, but there is a high possibility of unintended overlap with other components when a specification such as z-index: calc(var(--layer-stack-2) + 1);
is used. It is preferable to specify isolation
for the root of a component whose child elements have a z-index
specification.
Incidentally, before the advent of isolation
, there was a hack to generate stacking contexts by specifying transform
without side-effects (e.g. transform: scale(1)
).
Summary
- Specify
z-index
according to Layer Stack rules. - Specify
isolation: isolate
for component root
Original Link: https://dev.to/hiro0218/css-design-i-think-about-specifying-z-index-difficult-to-break-1koi
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To