Paweł Krystkiewicz
All articles

6 min read

Library quirks and coding preferences

Styled Components treats a property as unitless only when its key is camelCase. What happens when you skip that rule?

For two days, the initials in our Avatar component rendered at the wrong font weight. There were no console errors, no failing tests, and no lint warnings. The generated CSS contained font-weight: 500px. The browser discarded the declaration, and the text silently fell back to its parent's font weight.

The root cause was a small detail in styled-components: it treats a property as unitless only when the key is written in camelCase. If you write object styles with styled-components or emotion, you might have the same trap in your code right now.

Check your code first

Before I get into the story, here's the one command worth running today:

sh
grep -rnE "['\"](font-weight|line-height|z-index|flex-grow|flex-shrink)['\"]\s*:" src/

Look at each match and ask yourself: can this value ever be a number? If the answer is yes, you've found a potential bug.

The broken code

During a refactor, I moved the Avatar's base styles into a style factory: a function that returns a plain style object. The component then spread that object into the css prop. Here it is simplified to the bare minimum, with kebab-case keys spread straight into css:

jsx
const avatarTokens = (theme) => ({
  'border-radius': '50%',
  'font-weight': theme.typography.body.fontWeight, // the number 500 in theme A
});

const Avatar = ({ theme, children }) => (
  <span css={[{ display: 'inline-flex' }, avatarTokens(theme)]}>{children}</span>
);

Before the refactor, the component had written the CSS property itself using camelCase: fontWeight: tokens['font-weight']. The refactor removed that translation step.

The kebab-case keys weren't a mistake. They were the established convention in the codebase. Our migration guide from a few months earlier had explicitly told everyone to write CSS property keys as kebab-case strings.

Why 500 becomes 500px

babel-plugin-styled-components compiles the css prop into a regular styled component, so the object goes through the normal serializer. In styled-components 6.1.19, this happens in objToCssArray inside src/utils/flatten.ts:

ts
rules.push(`${hyphenate(key)}: ${addUnitIfNeeded(key, val)};`);

The relevant logic lives in src/utils/addUnitIfNeeded.ts:

ts
import unitless from '@emotion/unitless';
// ...
if (typeof value === 'number' && value !== 0 && !(name in unitless) && !name.startsWith('--')) {
  return `${value}px`;
}

Notice that addUnitIfNeeded receives the raw key, not the hyphenated version. The unitless map from @emotion/unitless (v0.8.1) only contains camelCase keys like fontWeight, lineHeight, and zIndex. So 'font-weight' in unitless evaluates to false, and any non-zero number gets a px suffix.

Meanwhile, hyphenate('font-weight') leaves the key unchanged, so the final CSS property name looks correct. That's what makes this bug particularly unpleasant: half the output is right, and the other half is silently wrong.

Reproduction

I compiled this example with babel-plugin-styled-components 2.3.0 and rendered it using ServerStyleSheet. Same values, different key styles:

jsx
const kebab = { 'font-weight': 500, 'line-height': 1.5, 'z-index': 10, opacity: 0.5, 'flex-grow': 1 };
const camel = { fontWeight: 500, lineHeight: 1.5, zIndex: 10, opacity: 0.5, flexGrow: 1 };

export const Kebab = () => <span css={[{ display: 'inline-flex' }, kebab]}>AB</span>;
export const Camel = () => <span css={[{ display: 'inline-flex' }, camel]}>AB</span>;

Here's the output with styled-components 6.1.19 in development mode:

text
Kebab  {display:inline-flex;font-weight:500px;line-height:1.5px;z-index:10px;opacity:0.5;flex-grow:1px;}
Camel  {display:inline-flex;font-weight:500;line-height:1.5;z-index:10;opacity:0.5;flex-grow:1;}

Nothing was logged. Note that opacity works either way because it's spelled the same in both formats.

This behavior isn't new. The same object passed to css() produces font-weight: 500px; line-height: 1.5px; z-index: 10px; in versions 5.3.11 and 6.4.3. Emotion (@emotion/serialize 1.3.3) also adds the px suffix to font-weight and line-height, though its development build does warn you (once per key) that kebab-case properties in objects aren't supported.

What the browser does with it

I loaded both rules in headless Chrome 156 on a span inside a 16px, weight-400 parent, then read the styles back from the CSSOM:

text
.kebab -> display: inline-flex; line-height: 1.5px; opacity: 0.5;
.camel -> display: inline-flex; font-weight: 500; line-height: 1.5; z-index: 10; opacity: 0.5; flex-grow: 1;
kebab computed font-weight=400 line-height=1.5px
camel computed font-weight=500 line-height=24px

font-weight: 500px, z-index: 10px, and flex-grow: 1px are invalid, so the browser drops them without warning. line-height: 1.5px is actually valid, so it gets applied and you end up with 1.5-pixel line boxes. In this case, the silent drop is the better outcome.

Why it slipped through

Only one theme was affected. Theme B's factories returned font weights as strings ('400', '700'). Strings pass through unchanged, so { 'font-weight': '500' } correctly becomes font-weight: 500. Only theme A used the raw number 500.

Our unit tests never saw real CSS. The Jest setup used @swc/jest, which doesn't run babel-plugin-styled-components. The css prop was never turned into actual CSS during tests. The token test only asserted that the returned object looked correct.

There was no runtime warning. Styled-components stays quiet, and browsers don't log dropped declarations.

Finally, the convention told us to write it this way.

A colleague spotted the bug two days later. The initials had lost their intended weight, inherited from the parent, and appeared heavier than before. It wasn't the first occurrence either. Another component had previously moved styles into tokens and, in the same change, added a helper to map kebab-case tokens to camelCase. The knowledge existed. It just hadn't spread beyond that one component.

The fix

My colleague fixed it locally in Avatar by mapping back to camelCase (fontWeight: tokens['font-weight'] and similar). It worked, but it was the second copy of the same workaround. That same day we changed the convention: CSS property keys in token objects would now use camelCase (fontWeight, backgroundColor). Only selector keys like '&:hover' would remain strings. As a bonus, we could now use dot notation (tokens.fontWeight) instead of bracket access.

Over the following weeks we sent a series of small PRs to update the remaining factories. The last one removed the mapper from Avatar, letting it spread the factory output directly again.

Guard rails

A rule that exists only in documentation is easy to forget. We added two checks to enforce the new convention.

A test for the token factories. We added a test that fails if it finds kebab-case CSS keys in any token factory. It started with an allowlist for files that hadn't been converted yet. As we updated the remaining factories, the allowlist shrank to zero and was eventually removed.

Here's how I'd write a test like this today. Instead of parsing source files, we call each factory and inspect the returned objects. We check every kebab-case key against the same unitless list that the serializer uses:

js
import unitless from '@emotion/unitless';
import * as factories from '../tokens';
import { themes } from '../themes';

const toCamel = (key) => key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());

// Kebab-case keys whose camelCase twin is unitless: a number here becomes `px`.
const trapKeys = (styles, path = []) =>
  Object.entries(styles).flatMap(([key, value]) =>
    value && typeof value === 'object'
      ? trapKeys(value, [...path, key])
      : key.includes('-') && toCamel(key) in unitless
        ? [[...path, key].join(' > ')]
        : [],
  );

test.each(Object.entries(factories))('%s has no px traps', (_name, factory) => {
  for (const theme of Object.values(themes)) {
    expect(trapKeys(factory(theme))).toEqual([]);
  }
});

This catches font-weight, line-height, and -webkit-line-clamp. It ignores border-radius or semantic names like text-color because they aren't in the unitless map. It also walks into nested objects such as &:first-child.

A lint rule for everything else. The test doesn't catch style objects written inline in components, so we added a lint rule as well. This no-restricted-syntax entry requires no additional plugins and only targets keys where passing a number would change the meaning:

js
const UNITLESS_KEBAB =
  '/^(font-weight|line-height|z-index|flex-(grow|shrink)|aspect-ratio|column-count|tab-size|' +
  'animation-iteration-count|grid-(row|column)(-(start|end|span))?|border-image-(outset|slice|width)|' +
  '(fill|flood|stop|stroke)-opacity|stroke-(width|dasharray|dashoffset|miterlimit)|-webkit-line-clamp)$/';

'no-restricted-syntax': ['error', {
  selector: `Property[key.type='Literal'][key.value=${UNITLESS_KEBAB}]`,
  message: 'Kebab-case unitless CSS key: styled-components appends "px" to a number. Use camelCase.',
}],

With ESLint 9.39.1 it caught 10 errors in the original buggy Avatar factory. The rule matches on the key rather than the value, since a linter can't know the runtime type. If your config already contains a no-restricted-syntax entry, you can merge this selector into it.

Across roughly 1,500 source files it found only two matches, both '-webkit-line-clamp': '3'. Those were harmless because the values were strings. Change the value to the number 3 and you'd get 3px. That's exactly the kind of subtle trap a lint rule is meant to catch.

If your codebase never intentionally uses kebab-case keys for CSS properties, a simpler rule that flags any quoted key matching /^-?[a-z]+(-[a-z]+)+$/ works well. Just be aware it will also match aria-label, data-testid, and lowercase HTTP headers, so it only makes sense in codebases that don't use quoted keys for those.

The part that stings

No one made a careless mistake. Everyone followed the guide, and the guide itself prescribed the bug. Code review checks whether code follows conventions, so it had no chance of catching this. The only part of the system that disagreed with the documentation was the serializer, and it didn't warn us.

Before you establish a convention, it's worth running it through the same five-line reproduction you'd use to test any other piece of code.