Polyfill CSS using styled-components mixins in React
With an example of flex gap polyfill

Brief intro of styled-components and flex gap
Styled-components is a modern way to add styles to React projects. Unlike SCSS/SASS which is using a separate pipeline to compile styling code to CSS, styled-component allows us to write CSS using an SCSS-like syntax mixed with JavaScript, and it applies generated styles to the target React component without needing to worry about class name conflicts.
The CSS property gap
is a new rising star in the flexbox feature family. It is used to express the spacing between child items within a flex container without the headache of margin
.
Imagine that:
- We defined a
StyledParent
component as the flex container, which says the child items within it should have a space of8px
in between - We defined a
StyledChild
component as the flex item, which renders a gray box with fixed height and width - We placed three
StyledChild
within aStyledParent
, as the code described below:
Then we could see that 8px
spacing is applied between the three gray boxes:

More in-depth explanation[1] and browser compatibility status[2] can be found in the references section.
Polyfill with styled-components using mixins
Not all modern CSS properties are supported in the browsers where your application need to run, and you can either choose to not use them or apply polyfill.
A traditional way of polyfill CSS is to use a post-processing tool such as PostCSS
to identify and add polyfills to the final stylesheet after bundle. But with styled-components
, we have another choice — mixins
.
The concept of mixins
is similar to SCSS/SASS: a function that generates reusable CSS blocks — in our context, it is just a JavaScript function!
That is, we want to write a JavaScript function to:
- detect if the browser supports the feature
- if supported, we generate the latest version of CSS without polyfill
- if not supported, we generate the polyfilled CSS
For example, we would like to replace…
export const StyledParent = styled.div`
display: flex;
gap: 8px;
`;
…with…
export const StyledParentWithMixin = styled.div`
display: flex;
${flexGap("8px")}
`;
…and the implementation is straightforward
Note: the polyfill code provided in this article is not the complete solution that covers every edge cases, but it works well for simple usages (e.g., use absolute values for
gap
)
You might wonder why we need to detect CSS feature support with JavaScript but not supports
— that is because sometimes it is very hard to do so without using JavaScript[3].
The detection code can be found below:
A note here is that the actual detection logic will run only once in runtime, and use the cached result for all following calls, so the performance won’t be affected.
Playground
References
More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.