Skip to content

[RFC] enhanceDensity — normalize components into a consistent scale #48746

Closed

Description

@siriwatknp

What's the problem?

Material UI components ship the comfortable Material Design spacing. Teams building data-dense, professional UIs (dashboards, admin consoles, design tools) routinely need denser layouts — and some need roomier ones.

There's an existing Density page, but it's a per-component workaround, not a density system:

  • No single mechanism. It's a grab-bag of defaultProps — size: 'small' on Button, dense: true on ListItem, variant: 'dense' on Toolbar, margin: 'dense' on inputs — a different prop per component.
  • Only 13 components. Button, Fab, FilledInput, FormControl, FormHelperText, IconButton, InputBase, InputLabel, ListItem, OutlinedInput, Table, TextField, Toolbar — nothing else.
  • One step, one direction. A single "denser" toggle; no tunable scale, no roomier direction.
  • Not holistic — by its own warning. The page states "you should not apply this theme to your whole application," so it can't be the app-wide density dial teams actually want.

Beyond that page, the only levers are styleOverrides and sx calc — re-deriving every component's internal pixel math by hand, per size. There is no single, predictable knob.

Even at the defaults, control sizes don't line up. A "medium" form row mixes a 36.5px Button, a 56px outlined TextField, a 40px IconButton and a 42px Checkbox hit area; the same control shifts height across variants (a standard-variant input box is ~32px vs 56px outlined/filled). The defaults are per-component pixel math, not a shared scale — nothing a theme can turn aligns them.

Material 3 itself documents spacing as a deliberate, adjustable system — compact vs. comfortable off one consistent scale (Applying spacing). A Material UI app can't express that today without forking component source.

This RFC proposes one built-in, opt-in enhancer — enhanceDensity(theme, scale?). The library ships one canonical scale; denser and roomier are userland recipes. An unconfigured app renders today's exact pixels (Argos zero-diff) and ships no extra CSS variables.

What are the requirements?

  1. Non-breaking, minimal cost when unused. An unconfigured theme is pixel-identical to today (Argos zero-diff) for every (variant, size) cell, and emits no extra vars.
  2. Theme configurable. Density is set at the theme level — no per-component editing, no calc for the consumer — and rides the existing theme tokens (theme.spacing, shape.borderRadius, theme.typography) instead of minting parallel ones.
  3. Coherent size. Spacing, sizing and (for components with a size-carrying prop) font/icon size reflow together — denser padding never pairs with full-size text — and control heights align across components.

Proposed solution

One public entry. enhanceDensity re-authors the whole component library onto one shared scale so sizing stays consistent across components. This is not proportional shrinking: each component maps its own dimensions to the scale's steps, and anchor controls converge on a dedicated touchTarget value, icon size via iconSize, so the misaligned defaults above line up by construction.

import { createTheme, enhanceDensity } from '@mui/material/styles';

// Pixel-identical to today — nothing applied.
const theme = createTheme({ cssVariables: true });

// enhancer standardize every components with a dedicated scale
const enhanced = enhanceDensity(createTheme({ cssVariables: true }));

There are deliberately no built-in density modes. An earlier draft of this RFC proposed a 'high' | 'medium' | 'low' mode argument. That was dropped: the modes shared all their code, and a mode enum forces the library to own three sets of design values that properly belong to a product. Denser and roomier ship as documented copy-paste recipes instead.

The scale

Key Default Kind
xxSmall … xxLarge 4 / 8 / 12 / 16 / 24 / 32 / 48 px spacing steps
touchTarget 32px sizing constant
iconSize 16px sizing constant

The seven steps space things: they ship as --mui-spacing-* CSS variables and theme.spacing('small') resolves them. The two constants size things: they ship as --mui-touchTarget / --mui-iconSize — their own namespace, deliberately not under --mui-spacing-* — and because they are not spacing keys, theme.spacing() does not resolve them. The override object mirrors that split: the seven steps nest under spacing, the two constants sit beside it.

enhanceDensity(theme, {
  spacing: { small: 10 },
  touchTarget: 28,
});

Per-size ramps derive from the constants — small = calc(touchTarget − $token), large = calc(touchTarget + $token) — so moving one constant carries all three sizes rather than only the middle one.

The scale is closed. The override object is strictly typed; a misspelled key is a compile error, and new step names cannot be added. Registering user-defined steps was spiked and declined — the steps line components up precisely because there are few of them. For a value the ladder doesn't carry, apps use a multiple of the spacing unit, which theme.spacing() has always accepted.

Use the scale

The scale reads back off the theme, so app-level customization sits on the same ladder the components reflow on — no second set of numbers to keep in sync.

// Spacing steps — in any CSS property, a `styleOverrides` callback, or `styled`.
theme.spacing('medium'); // '16px' (static) / 'var(--mui-spacing-medium, …)' (cssVariables)
theme.spacing('-xSmall'); // a leading dash negates

<Box sx={{ p: 'small', gap: 'xSmall' }} />;

// Sizing constants — not spacing keys, so read them off the theme instead.
const Control = styled('div')(({ theme }) => ({
  height: (theme.vars || theme).touchTarget,
  '& svg': { fontSize: (theme.vars || theme).iconSize },
}));

theme.vars carries the variable reference, so the value keeps following a --mui-touchTarget override scoped to a region; the plain theme carries the resolved length. The theme.vars || guard is what makes one customization work on both theme shapes. Both constants are undefined until enhanceDensity has run — density is opt-in, and the types say so.

How it ships

  • the scale append to theme.spacing()
  • sx takes the same names — <Box sx={{ p: 'small', gap: 'xSmall' }} />
  • Emitted theme overrides — zero component-source changes. The enhancer computes each component's values off the scale and emits them as styleOverrides against selectors the components already ship. Nothing applied → nothing emitted → today's exact pixels.
  • Private CSS variables (--_*) are used for components with multiple slots that needs to be in synced without breaking apart, e.g. Inputs, Autocomplete, Switch
  • Overrides land where the element renders — root by default, the portal slot when the styled element renders through a portal.
  • Gaps replace sibling margins wherever the layout allows, so there's one value to override instead of a margin pair.
  • Three theme channels are written: components.Mui*.styleOverrides, components.Mui*.defaultProps (for JS-gated dimensions), and theme.mixins.toolbar. createTheme always fills the toolbar mixin with the stock 56/48/64px heights, so the enhancer overrides it with the same heights as the regular Toolbar (touchTarget + 2·xSmall, touchTarget + 2·xxSmall in landscape). Without that, an app that offsets a fixed AppBar with the mixin spacer gets a gap or an overlap. Only the height keys are replaced; other keys in a custom mixin are kept.

Decision

Agreed on how this lands:

  • It ships as an experimental API. The enhancer is exported as unstable_enhanceDensity and imported aliased — import { unstable_enhanceDensity as enhanceDensity } from '@mui/material/styles' — the same shape as unstable_ClassNameGenerator.
  • The docs live under Experimental APIs, not Customization. The existing customization/density page keeps its size/dense guidance unchanged.
  • No release-note entry, no announcement. The API stays deliberately unadvertised while it is unstable, so the surface can still change without a breaking-change cycle.
  • Coverage is the component set mapped today. Components outside that mapping are not covered, and extending it is not committed.

Need Decisions

Scale naming — decided: camelCase

Keeps existing size naming small medium large, using x* as tails for expanding the scale. Options considered:

  1. plain: xsmall xxsmall xlarge etc
  2. hyphen: x-small xx-small x-large etc
  3. camel: xSmall xxSmall xLarge etc — decided

Camel gets the same quote-free object as plain (enhanceDensity(…, { spacing: { xxSmall: 2 }, touchTarget: 24 })) while keeping the xx tails readable, and it matches how the theme already names multi-word keys in CSS variables (--mui-shape-borderRadius, --mui-opacity-inputPlaceholder) — so the steps emit as --mui-spacing-xxSmall. The two sizing constants follow the same rule: touchTarget, iconSize.

Sx typings

  • should sx handle scale autocompletion? when type sx={{ p: <show scale> }}. I lean toward skipping this as it requires changes on MUI System on the type level

Extensibility

  • should the scale be extensible? meaning user can add more keys to the scale. I lean toward skipping this too.

Search keywords: density, compact, comfortable, spacing scale, touch target

Activity

  1. added
    RFC
    package: material-ui
    on Jun 30, 2026
  2. mj12albert commented on Jul 1, 2026

    @mj12albert
    Member

    Could we consider an API surface similar to breakpoints:

    // Opt-in by explicitly setting `density`
    const theme = createTheme({
      cssVariables: true,
      density: {
        scale: 'compact', // 'normal' | 'comfortable' | CustomDensityScale
      },
    });
    
    const theme = createTheme({
      cssVariables: true,
      density: {
        scale: {
          xxs: '2px',
          xs: '4px',
          sm: '6px',
          md: '8px',
          lg: '12px',
          xl: '18px',
          xxl: '24px',
        },
      },
    });

    I know we have the responsiveFontSizes/enhanceHighContrast precedent, but if these grow it starts to look awkward:

    const theme = responsiveFontSizes(
      enhanceHighContrast(
        enhanceDensity(createTheme({ cssVariables: true })),
      ),
    );

    Makes you wonder does the order of these matter? and whether at some point there could be conflicts if these were applied out of order

    As far as I can tell, the only technical benefit of the "enhancer function" API seems to be bundle size 🤔

  3. siriwatknp commented on Jul 2, 2026

    @siriwatknp
    MemberAuthor

    As far as I can tell, the only technical benefit of the "enhancer function" API seems to be bundle size 🤔

    That's the main benefit, the other crucial one is that I don't want the default scale to be opinionated.

  4. changed the title [-][RFC] enhanceDensity — opt-in component density[/-] [+][RFC] enhance*Density — opt-in component density presets[/+] on Jul 10, 2026
  5. LukasTy commented on Jul 10, 2026

    @LukasTy
    Member

    Overall it looks very nice.
    Great direction and the solution looks super clean, especially compared to the initial explorations. 👌

    Product asks

    • enhanceNormalDensity is a naming hazard. "Normal" reads as a no-op, but it reflows onto the normalized scale and can diff against the unconfigured render. Either make it pixel-identical or rename it. Related: the X Data Grid already ships density: 'compact' | 'standard' | 'comfortable' -- aligning the vocabulary (Standard, Comfortable) keeps the product family coherent.
      In general, do we need the 3 densities besides the default one?
    • Enhancer composition (@mj12albert's concern): answer with guarantees rather than a redesign -- assert and test that the enhancers are idempotent and order-independent with responsiveFontSizes/enhanceHighContrast. A compose helper can come later without breaking anything.
    • Benchmark the applied cost. Zero cost when unused is proven; the unmeasured number is style-generation cost and emitted CSS weight when a preset is applied (every covered (variant, size) cell x slots). One benchmark line in the RFC would settle whether emission volume needs a budget.
    • MUI X follow-up. What plan do you see to achieve this for MUI X packages?
      I assume we'll need similar helper styling functions (possibly per package?) to handle it there.
      Or do you have other ideas?

    Prototype spot-check (#48749) against the RFC text

    I went through the prototype diff claim by claim. The architecture holds up: the --mui-density-* scale rides the theme's own vars channel exactly as described (including the no-CssBaseline and static-theme paths, unit-tested), slot/portal emission rules are followed (Tooltip tooltip/popper/arrow, Autocomplete listbox), base inheritance works as written (input padding on MuiInputBase, no MuiButtonBase emissions anywhere), the --_* var inventory matches the named set exactly, and the public surface is the three presets with no options. Since "the emitted overrides + per-component mapping are what this RFC signs off", the remaining text-vs-code mismatches are worth fixing (in the RFC or in the emissions) before sign-off:

    • Requirement 5's type/icon story doesn't match the implementation. (a) The named per-size examples don't reflow: Button/ToggleButton emissions are padding-only; compact instead moves the shared typography.button token 14px -> 13px, which collapses small == medium (comfort collapses medium == large at 15px) -- "Button small != large, ToggleButton 13/15" never moves per size. (b) The "no size-carrying prop -> type frozen" rule is deliberately broken by compact: Tooltip 11px -> 10px, Tab base 14px -> 13px, AccordionDetails pinned at 0.875rem (all marked "compact-only type" in code comments). (c) Icons aren't fed by the typography config: SvgIcon 18/20/30 are inline literals (compact-only), Chip icons calc off --_height, and the "Rating star 18/24/30" example has no implementation. The prototype's behavior looks like a defensible design -- it's just not the one requirement 5 describes, so I'd rewrite that paragraph around what the code actually does.
    • Staged-coverage corrections. MuiIconButton and MuiRating appear nowhere in the diff despite both being listed as "draft emissions staged in the presets". And SvgIcon -- one of the 10 verified families -- reflows only under compact (normal/comfort intentionally emit nothing); the coverage claim should say so.
    • The guard net is narrower than described. Readback parity value-checks only the surfaced playground subset (registeredFieldIds, with function-matcher rows skipped except one Tab case) -- staged rows in the ~220-row table are never checked against the presets. The generated table header says "CI diffs this file" but no CI job re-runs density:codegen. The PR body's "compact/comfort reflow captures" for density:shot is off twice: the actual levels are dense/loose (review-only), and they set per-component tokens from the [material-ui] CSS-var density adapter experiment #48624 architecture that nothing in this emission-based PR consumes, so they cannot show reflow. Before the rollout leans on these guards, I'd wire the codegen freshness check into CI, extend parity to the full table, and refresh the harness -- ideally making the generated table the canonical mapping dataset (presets verified against it in full, coverage reports derived from it).
    • "Zero component-source changes" has one undisclosed exception. formControlLabelClasses.ts gains a labelPlacementEnd key the presets need for a :has() selector. It's behavior-neutral (the DOM class was already emitted at runtime), but the absolute claim and its checked box should disclose it.
    • Wording drift to fix in one pass. "Emits ONE private CSS var" vs the 2-3 seed vars the RFC itself enumerates (filled/standard/Autocomplete); the outlined bridge names --_shrinkY, but shrink is never density-driven for outlined (hardcoded master literal, per the code's own comment); --_height/--_arrowSize/--_restY/--_shrinkY aren't component-prefixed despite decision 3; tag values ride the tag slot, not root; a few spacing seeds are tuned raw px (--_filledInputPadTop: 20px, frozen --_inputMarginTop: 16px) against requirement 5's absolute "spacing off the shared scale".
    • Housekeeping. The two ADRs are referenced from the RFC and from in-PR files (harness README, playwright config) but exist only on the [material-ui] CSS-var density adapter experiment #48624 branch; the playground export help text says to render <CssBaseline /> "so the density variables materialise", contradicting the mechanism, the exported file's own header, and the tests; buttons.a11y.json looks like an unrelated stray change; the public DensityScale type export contradicts densityScale.ts's own "not re-exported from the barrel" comment -- align one or the other.
  6. changed the title [-][RFC] enhance*Density — opt-in component density presets[/-] [+][RFC] enhanceDensity — normalize components into a consistent scale[/+] on Sep 2, 2026
  7. mnajdova commented on Sep 2, 2026

    @mnajdova
    Member

    One small question/note.

    The seven steps space things: they ship as --mui-spacing-* CSS variables and theme.spacing('small') resolves them. The two constants size things: they emit as plain lengths, get no CSS variable, and theme.spacing() does not resolve them. Per-size ramps derive from the constants — small = calc(touch-target − x-small), large = calc(touch-target + small) — so moving one constant carries all three sizes rather than only the middle one.

    Are x-small and small used as a step here just an example (e.g. component logic), or is it something we prescribe? Will people need to learn how these affects different component sizes?

  8. github-actions commented on Nov 23, 2026

    @github-actions
    Contributor

    This issue has been closed. If you have a similar problem but not exactly the same, please open a new issue.
    Now, if you have additional information related to this issue or things that could help future readers, feel free to leave a comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    RFCpackage: material-ui

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions