Sub topic 1
The problem: clipped and buried UI
Some UI has to appear above everything else on the page: modals, dropdown menus, tooltips, toasts. In React you usually write these components next to the thing that triggers them, which puts their DOM nodes deep inside the triggering component's ancestors. Those ancestors can clip the UI or push it behind other content, and CSS offers no clean way around either problem. This chapter explains the two failure modes and why the usual quick fixes break. Later chapters introduce portals as the solution.
Prerequisites
This chapter assumes you already know:
- How to write function components in JSX and pass props and
children. useStateanduseEffectat a basic level.- Basic DOM concepts: nodes,
document.body, and event bubbling. - Basic CSS positioning (
static,relative,absolute,fixed) and thez-indexproperty.
You do not need to know anything about portals yet.
Where the problem comes from
React's usual model is that a component's output lands where the component is rendered. If <Dropdown> is rendered inside <Card>, its DOM nodes become descendants of the card's DOM node. That is convenient for code organisation, because the dropdown lives next to its trigger. It is a problem for layout, because CSS applies rules based on the DOM ancestors of an element. Two CSS features cause most of the trouble:
- Clipping: an ancestor with
overflowset to anything other thanvisiblecan cut off its descendants. - Stacking contexts: an ancestor can trap its descendants'
z-indexvalues in a private ranking, so a largez-indexinside it has no effect outside.
A third behaviour, a changed containing block for position: fixed, produces the same symptoms and is covered below.
Failure mode 1: clipped by overflow
Here is a card that shows a dropdown menu. The card uses overflow: hidden so that its rounded corners also crop an image.
import { useState } from 'react';
import './styles.css';
export default function App() {
return (
<div className="page">
<Card />
</div>
);
}
function Card() {
const [open, setOpen] = useState(false);
return (
<div className="card">
<div className="card-header">
<button onClick={() => setOpen((o) => !o)}>Actions</button>
{open && (
<ul className="menu">
<li>Edit</li>
<li>Duplicate</li>
<li>Delete</li>
<li>Archive</li>
</ul>
)}
</div>
<p>A short card body.</p>
</div>
);
}.page {
padding: 40px;
}
.card {
position: relative;
width: 260px;
height: 120px;
border-radius: 12px;
overflow: hidden;
border: 1px solid #ccc;
}
.card-header {
position: relative;
padding: 8px;
}
.menu {
position: absolute;
top: 100%;
left: 8px;
margin: 0;
padding: 4px 0;
list-style: none;
background: white;
border: 1px solid #ccc;
width: 160px;
}The menu is four items tall, but the card is only 120 pixels high. When you click the button, the part of the menu that extends past the bottom edge of the card is cut off. The "Archive" item may be partly or fully invisible.
The browser works as designed here. An overflow value other than visible makes the element clip its content to its padding box. That includes absolutely positioned descendants, as long as the element is in the descendant's containing-block chain. Here the card is position: relative, so it is also the containing block for the menu's nearest positioned ancestor chain, and the clip applies.
An edge case: not every ancestor clips
overflow clips only descendants whose containing block is the clipping element or something inside it. An absolutely positioned element whose containing block is an ancestor outside the clipping element is not clipped by it. This is why the bug is easy to miss. It appears only when the nearest positioned ancestor sits inside, or is, the element with overflow set. Adding position: relative to a wrapper "for convenience" can suddenly make a previously working dropdown get cropped.
Also note that overflow: auto and overflow: scroll do not crop invisibly. They add scrollbars, so the menu forces the container to scroll, which is usually worse.
Failure mode 2: buried by stacking contexts
The second problem is that the element is visible but sits behind something else. Most developers' mental model of z-index is "bigger number wins". The real rule is more local.
A stacking context is a self-contained group of elements that are ordered together. Inside a stacking context, descendants are ranked by z-index. The whole context then takes part in its parent context as a single unit, ranked by the z-index of the element that created it. A child can never rise above a sibling context of its ancestor, however large its own z-index is.
Common things that create a stacking context:
| Trigger | Notes |
|---|---|
| The root `<html>` element | Always one root context. |
| `position: relative` or `absolute` with `z-index` other than `auto` | The most common cause. |
| `position: fixed` or `sticky` | Always creates a context. |
| `opacity` less than 1 | Easy to add by accident for a fade effect. |
| `transform`, `filter`, `perspective`, `clip-path` set to anything but `none` | Includes `translateZ(0)` used as a performance hint. |
| `will-change` naming a property that would create one | For example `will-change: transform`. |
| `isolation: isolate` | Made specifically to create a context. |
| `contain: paint` or `layout` | Also changes the containing block. |
| A flex or grid child with `z-index` other than `auto` | Works even without `position`. |
Here is a reproduction:
export default function App() {
return (
<div className="layout">
<aside className="sidebar">
<div className="tooltip">Tooltip with z-index: 9999</div>
<button>Hover target</button>
</aside>
<main className="content">Main content</main>
</div>
);
}.layout {
position: relative;
display: flex;
}
.sidebar {
position: relative;
z-index: 1;
width: 180px;
padding: 16px;
background: #eef;
}
.content {
position: relative;
z-index: 2;
flex: 1;
padding: 16px;
background: #efe;
}
.tooltip {
position: absolute;
left: 140px;
top: 0;
z-index: 9999;
width: 200px;
padding: 8px;
background: #222;
color: white;
}The tooltip extends to the right, beyond the sidebar, over the main content. Despite z-index: 9999, the main content paints over it. The sidebar has position: relative and z-index: 1, so it is a stacking context ranked 1. The main area is a sibling context ranked 2. The tooltip's 9999 is only compared with other elements inside the sidebar. At the layout level, the whole sidebar, tooltip included, ranks below the main area.
Accidental contexts
Stacking contexts are often created by a style that has nothing to do with layering. Someone adds transform: translateX(0) for an animation, or opacity: 0.99 to fix a rendering glitch, and a distant dropdown starts hiding behind its neighbour. Because the cause is a style on an ancestor several levels up, this class of bug is slow to find. Browser developer tools help here. Walk up the element's ancestors and look for any rule from the table above.
Failure mode 3: `position: fixed` that is not fixed
Modals are normally position: fixed with inset: 0 so they cover the viewport. This works only if the element's containing block is the viewport. If any ancestor has a transform, perspective, filter, will-change: transform, or contain: paint (or layout), that ancestor becomes the containing block for fixed-position descendants. The "full-screen" overlay then covers only that ancestor's box.
export default function App() {
return (
<div className="animated-panel">
<p>Panel content</p>
<div className="overlay">I should cover the whole screen</div>
</div>
);
}.animated-panel {
width: 300px;
height: 200px;
transform: translateY(0);
border: 1px solid #999;
}
.overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
color: white;
}The overlay is sized to the 300 by 200 panel, not the browser window. Removing the transform from the panel restores the expected behaviour.
Why the usual fixes fall short
When developers hit these problems, they typically try a few workarounds:
- Raise
z-index. This fixes nothing when an ancestor context is the cause, and it starts a numbers race (9999,99999, ...) that nobody can reason about. - Remove
overflow: hidden. This breaks the effect it was added for, such as rounded corners cropping an image. You then need extra wrappers to restore it. - Move the component higher in the JSX. This couples unrelated components. A dropdown that belongs to a table cell would have to be rendered by the page and wired back down with props.
- Compute positions with JavaScript and use
position: fixed. This works only if no ancestor changes the containing block, and you now maintain scroll and resize logic.
All of these fight the real cause. The element is in the wrong place in the DOM. The component tree and the DOM tree are tied together, so a component that belongs logically to a card must also sit physically inside the card's element.
The fix in outline
What these cases need is to keep the component where it is in the React tree, so props, state, and context stay simple, but to place its DOM nodes somewhere else, typically as a direct child of document.body. At the top level of the document, no ancestor can clip it, trap its z-index, or change its containing block.
React provides this with createPortal, which the next chapters cover:
import { createPortal } from 'react-dom';
function Menu({ children }) {
return createPortal(
<ul className="menu">{children}</ul>,
document.body
);
}You do not need to understand this snippet fully yet. It only shows the shape of the solution: the same component, with its output attached to a different DOM node. Positioning the menu next to its trigger then becomes your job, usually by measuring the trigger with getBoundingClientRect(). That trade-off, and how to handle it, comes in later chapters on tooltips and popovers.
A diagnostic checklist
When a floating element is cut off or hidden, check these in order:
- Is the element cropped, or covered? Cropped content points to
overflow. Covered content points to stacking. - For cropping, walk up the ancestors and find the first one with
overflowother thanvisible. Check whether it contains the element's containing block. - For covering, find the nearest ancestor that creates a stacking context, then compare its rank with the element that covers yours, at the level where their contexts first share a parent.
- For a fixed element that is not full-screen, look for
transform,filter,perspective,will-change, orcontainon an ancestor. - If you find one, ask whether the style can be removed. If it can't, the element probably belongs outside that ancestor in the DOM.
Exercise
A page has a header with position: relative; z-index: 10 and a content area with position: relative; z-index: 20. A dropdown inside the header has position: absolute; z-index: 1000 and extends down into the content area. Will the dropdown appear above the content area's text? Why or why not, and what is one way to fix it without changing the header's or content's z-index?
Show answer
No. The header is a stacking context with rank 10, and the dropdown's 1000 is only compared with other elements inside the header. The content area is a sibling context with rank 20, so the whole header, dropdown included, is painted below it. A fix that leaves both z-index values alone is to render the dropdown through a portal into document.body, so it is no longer a descendant of the header and takes part in the root stacking context.
Exercise
A full-screen modal overlay uses position: fixed; inset: 0, but it only covers a small box inside a sidebar. The sidebar has no overflow rule and no z-index. What property on the sidebar or one of its ancestors is the likely cause?
Show answer
An ancestor has a property that makes it the containing block for fixed-position descendants, such as transform, filter, perspective, will-change: transform, or contain: paint or layout. The overlay is then sized relative to that ancestor instead of the viewport.