Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress ๐Ÿ’…

Last update: May 17, 2022

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress ๐Ÿ’…

downloads: 600k/month Join the community on Spectrum gzip size module formats: umd, cjs, esm Code Coverage

Looking for v5?

The master branch is under development of the upcoming v6 major version of styled-components. For changes targeting v5, please point your PRs at the legacy-v5 branch.


Utilising tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components allows you to write actual CSS code to style your components. It also removes the mapping between components and styles โ€“ using components as a low-level styling construct could not be easier!

const Button = styled.button`
  color: grey;
`;

Alternatively, you may use style objects. This allows for easy porting of CSS from inline styles, while still supporting the more advanced styled-components capabilities like component selectors and media queries.

const Button = styled.button({
  color: 'grey',
});

Equivalent to:

const Button = styled.button`
  color: grey;
`;

styled-components is compatible with both React (for web) and React Native โ€“ meaning it's the perfect choice even for truly universal apps! See the documentation about React Native for more information.

Supported by Front End Center. Thank you for making this possible!

Upgrading from v4

  1. npm install [email protected]^5.0.0 [email protected]^16.8 [email protected]^16.8 [email protected]^16.8
  2. ??
  3. Profit!

If you use jest-styled-components, make sure you update that too.

Docs

See the documentation at styled-components.com/docs for more information about using styled-components!

Quicklinks to some of the most-visited pages:

Example

import React from 'react';

import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// Use them like any other React component โ€“ except they're styled!
<Wrapper>
  <Title>Hello World, this is my first styled component!</Title>
</Wrapper>

This is what you'll see in your browser:

Babel Macro

If you're using tooling that has babel-plugin-macros set up, you can switch to the styled-components/macro import path instead to gain the effects of the babel plugin without further setup.

import styled from 'styled-components/macro';

// A static className will be generated for Title (important for SSR)
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

If you wish to provide configuration options to the babel plugin similar to how you would in a .babelrc, see this guide. The config name is "styledComponents".

Built with styled-components

A lot of hard work goes into community libraries, projects, and guides. A lot of them make it easier to get started or help you with your next project! Thereโ€™s also a whole lot of interesting apps and sites that people have built using styled-components.

Make sure to head over to awesome-styled-components to see them all! And please contribute and add your own work to the list so others can find it.

Contributing

If you want to contribute to styled-components please see our contributing and community guidelines, they'll help you get set up locally and explain the whole process.

Please also note that all repositories under the styled-components organization follow our Code of Conduct, make sure to review and follow it.

Badge

Let everyone know you're using styled-components โ†’ style: styled-components

[![style: styled-components](https://img.shields.io/badge/style-%F0%9F%92%85%20styled--components-orange.svg?colorB=daa357&colorA=db748e)](https://github.com/styled-components/styled-components)

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! ๐Ÿ™ [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

Licensed under the MIT License, Copyright ยฉ 2016-present Glen Maddern and Maximilian Stoiber.

See LICENSE for more information.

Acknowledgements

This project builds on a long line of earlier work by clever folks all around the world. We'd like to thank Charlie Somerville, Nik Graf, Sunil Pai, Michael Chan, Andrey Popp, Jed Watson & Andrey Sitnik who contributed ideas, code or inspiration.

Special thanks to @okonet for the fantastic logo.

GitHub

https://github.com/styled-components/styled-components
Comments
  • 1. Separate HTML attributes from styling props

    Background

    I am trying to style a 3rd party "masked" input. The styles are applied correctly, however, there are props I pass into the "styled" element that are used within the CSS logic of the styled component that I don't want passed down to the 3rd party input. This logs an error saying there are undesired props being put on the input (this is also an issue with the 3rd party component that isn't properly stripping out what should go on the input).

    I could see it being an enhancement where we specify what props to terminate at the "styled" part. However, this also could just be looked at as the 3rd party component having an issue not removing those props. I'm fine with it being an issue with the 3rd party developer but just wanted to mention the issue and see if this is happening to other people and if it is worth it to build some extra logic in.

    Screenshot

    screen shot 2017-01-31 at 11 31 51 am

    Reviewed by jspangler at 2017-01-31 16:40
  • 2. v4 beta constructive feedback

    Please provide as much detail as possible when commenting here so we can help! A huge amount of time and thought has been put into the API changes. We know it won't be a "flip a switch" situation, but the ergonomics of the library going forward should be markedly better and more flexible.

    Reviewed by probablyup at 2018-09-04 22:33
  • 3. Discuss SSR API and methods

    I just want to kick off a discussion to finalise our SSR API.

    So API came from the comments on the #214

    const { css, html } = StyleSheet.collect(() =>
      ReactDOMServer.renderToString(<App />)
    );
    

    Please feel free to suggest what the API will look like, (let the bikeshedding begin!)

    Also if we're already doing de-duping in SSR level, do we even need reset()? (related issue #378) Or would that just be a convenience function since we don't need it anymore?

    cc @mxstbr / @geelen

    Reviewed by thisguychris at 2017-01-18 19:26
  • 4. How do I provide props to styled elements in Typescript?

    I looked at the docs and other than creating a whole empty component purely for providing a definition of props I'm not sure of if it's possible to provide custom props to a styled element other than theme.

    Example

    image

    For the above example I don't know how to make it not error.

    Reviewed by tal at 2017-03-30 21:38
  • 5. Use insertRule in browser

    Premlinary patch for using insertRule api. Seems to help performance quite a bit, but the implementation is kind of hacky. I'm just using a naive regexp to split up rules but I'm looking to use a stylis middleware (@mxstbr has suggested looking into https://github.com/thysultan/stylis.js/issues/59 and https://github.com/threepointone/glam/issues/5 for reference)

    Edit by @philpl: Updated to respect and enforce component order (out of order injection) and to rehydrate into a new SpeedyBrowserTag purely using insertRule. This also removes a couple of APIs from the BrowserTags that are not needed in production.

    Reviewed by schwers-zz at 2017-10-04 20:44
  • 6. Deprecate .extend in favour of only styled(Component)

    The FAQ explains the difference between styled() and .extend. However I wonder if it would be possible to take the decision out of the devs hand and have styled check for the handed in Component if its already a styled component. If it is .extend it otherwise create a new class.

    Was this considered at one point?

    Reviewed by pke at 2018-02-22 09:46
  • 7. 5.0 Roadmap

    Test it out:

    npm install [email protected] [email protected]^16.8 [email protected]^16.8 [email protected]^16.8
    

    5.0 milestone

    • [x] ~~rewrite stylesheet + tag classes for the needs of today (#2522)~~
    • [x] ~~move react-is to peer dependencies (https://github.com/styled-components/styled-components/pull/2187)~~
    • [x] ~~use react v16.7+ hooks to simplify the context consumer architecture (#2390)~~
    • [x] ~~babel 7 migration (maybe... there were bundle size regressions before) (#2509)~~
    • [x] ~~internal rewrite to use hooks (#2390)~~
    • [x] ~~bump minimum versions of react, react-native to hooks-compatible versions~~
    • [x] ~~remove code paths deprecated in v4 (https://github.com/styled-components/styled-components/pull/2604)~~
    • [x] ~~fix cGS style clobbering issues (https://github.com/styled-components/styled-components/pull/2824)~~

    5.1 candidate

    • [ ] stylis -> sweetsour (depending on when it's ready for use and testing)
    • [ ] figure out CSP / nonce support (#2363)
    • [ ] solution to drop the prop whitelist (https://github.com/styled-components/styled-components/pull/2093)
    • [ ] source maps for styles (https://github.com/styled-components/styled-components/issues/827)
    • [ ] scoping of styles via StyleSheetManager (https://github.com/styled-components/styled-components/issues/1789)

    didn't do

    • [ ] ~~use React.warn and React.error if 16.9 comes out before v5 (https://github.com/styled-components/styled-components/issues/2584)~~ React removed them

    follow along on the ~canary~ v5 branch

    evolving

    Reviewed by probablyup at 2018-08-21 06:30
  • 8. v2 prerelease feedback

    If you're using the v2 pre-release, please let us know in a comment below if it works well for you! If you encounter bugs, please submit individual issues for them!

    To try the v2 prerelease, use npm install [email protected] babel-plugin-styled-components and add the plugin to your Babel configuration like a regular Babel plugin. The plugin is optional as it only provides consistent naming for SSR as well as some pre-processing.

    Reviewed by mxstbr at 2017-02-04 11:17
  • 9. Babel transform

    ~~We need a way (probably babel transform?) to extract and precompile the static styles of our components!~~

    Extracting static styles is actually not what we want, we want to pre-parse the CSS in a build step but leave it in the JS: See this comment

    Has anybody done this before? I know I haven'tโ€ฆ

    Reviewed by mxstbr at 2016-10-13 09:40
  • 10. SSR Memory Leak with v5 release candidate 2

    Environment

    Default, Baseline

    ## System:
     - OS: macOS 10.15
     - CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
     - Memory: 3.11 GB / 32.00 GB
     - Shell: 5.6.2 - /usr/local/bin/zsh
    ## Binaries:
     - Node: 10.15.1 - ~/.nvm/versions/node/v10.15.1/bin/node
     - Yarn: 1.19.1 - ~/****/****/applications/site/node_modules/.bin/yarn
     - npm: 6.4.1 - ~/.nvm/versions/node/v10.15.1/bin/npm
    ## npmPackages:
     - babel-plugin-styled-components: ^1.10.0 => 1.10.6
     - styled-components: ^4.0.0 => 4.4.1
    

    After upgrade to RC 2

    ## System:
     - OS: macOS 10.15
     - CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
     - Memory: 3.11 GB / 32.00 GB
     - Shell: 5.6.2 - /usr/local/bin/zsh
    ## Binaries:
     - Node: 10.15.1 - ~/.nvm/versions/node/v10.15.1/bin/node
     - Yarn: 1.19.1 - ~/****/****/applications/site/node_modules/.bin/yarn
     - npm: 6.4.1 - ~/.nvm/versions/node/v10.15.1/bin/npm
    ## npmPackages:
     - babel-plugin-styled-components: ^1.10.0 => 1.10.6
     - styled-components: ^5.0.0-rc.2 => 5.0.0-rc.2
    

    Notes: Both environments use TypeScript, Next.JS and latest versions of react

    Steps to Reproduce

    1. Use the _document.js file found in the with-styled-components example of next.js.
    2. Have styled-components 4.4.1 installed.
    3. Run application using N|Solid from nodesource. Also could probably get this information by attaching chrome inspector to node.
    4. Run npx loadtest -c 5 --rps 10 -k -t 90 http://localhost:8080/
    5. See that memory usage has peaks and valleys, RSS and Heap memory allocation move together. External memory barely moves.
    6. install release candidate 2
    7. repeat the steps above.
    8. See that Heap allocation remains consistent, MORE consistent than in 4.4.1, but RSS and External memory allocation seem to climb indefinitely until the application crashes under load.
    9. Look at memory snapshot and see that ServerStyleSheet is massive, at around 2 gigabytes, and the server is holding onto array buffers and strings that seem to reference styles.

    Memory Timeline In N|Solid on version 4.4.1

    heapsnapshot image

    Memory Timeline in N|Solid on Version 5 RC 2

    heapsnapshot image

    Comparison of Heap snapshots

    image

    RC 2 is on the left. The snapshots were taken as close to the same point as possible (immediately following the load test that was run with the same stats: 5 concurrent threads, keep-alive connections, 10 requests per second for 90 seconds). The only change between the two is upgraded to RC 2.

    Reviewed by brad-decker at 2019-12-03 23:37
  • 11. Server Side Rendering: First paint missing some styles (FOUC)

    Environment

    System:

    • OS: macOS High Sierra 10.13.5
    • CPU: x64 Intel(R) Core(TM) i5-4308U CPU @ 2.80GHz
    • Memory: 82.71 MB / 8.00 GB
    • Shell: 3.2.57 - /bin/bash

    Binaries:

    • Node: 8.9.4 - ~/.nvm/versions/node/v8.9.4/bin/node
    • npm: 6.1.0 - ~/temp/Martin/metrics-dashboard/node_modules/.bin/npm
    • Watchman: 4.7.0 - /usr/local/bin/watchman

    npmPackages:

    • babel-plugin-styled-components: ^1.5.1 => 1.5.1
    • styled-components: ^3.2.6 => 3.2.6

    Reproduction

    The chunk of server side rendering code used:

            const sheet = new ServerStyleSheet()
            let html = ReactDOMServer.renderToString(sheet.collectStyles(
              <Provider store={store}>
                {<RouterContext {...renderProps} />}
              </Provider>
            ))
            const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()
    

    My index template (index.ejs) as such:

    <!DOCTYPE html>
    <html>
    
    <head>
      <%- styleTags %>
    </head>
    <body style="margin: 0; font-family: 'PT Sans', Arial;">
      <div id="root" style="height: 100%;">
        <%- html %>
      </div>
      <script type="text/javascript" charset="utf-8">
        window.__REDUX_STATE__ = '<%= reduxState %>';
      </script>
    
    </body>
    </html>
    

    And just in case some styled-component code, though I don't expect this to be the issue (possibly because of using extend?).

    //   H1.js file
    
    import styled from 'styled-components';
    
    const H1 = styled.h1.attrs({ className: 'h1' })`
        font-size: 4rem;
    `;
    
    export default H1;
    
    //   end of H1.js file
    
    //   WidgetTitle.js file
    import NormalH1 from "components/H1";
    
    const WidgetTitle = NormalH1.extend.attrs({ className: 'widget__title' })``;
    
    export default WidgetTitle;
    
    //   end of WidgetTitle.js file
    

    Steps to reproduce

    1. Server side rendering set up as shown above, following closely the steps here: https://www.styled-components.com/docs/advanced#server-side-rendering.

    Expected Behavior

    For all styles to be applied during first paint (like so below).

    First paint expected

    Actual Behavior

    Only some styles being applied on first paint, while some rules (specifically font-size) seems to be applied only after the JS bundle is parsed and executed.

    first paint missing font size rules

    Remarks

    As you can see in the two screenshots, I get a flash of content where the font-size rule isn't respected. I had this same issue with font-family actually, but dealt with it by putting it as an inline style on my <body> tag. Possibly this is a Flash of Unstyled Text (FOUT), but I'm honestly quite lost as to why these specific rules are being ignored on the first paint.

    I state that the rules seem to be applied only after the main JS bundle is loaded/parsed/executed because of examining the request for app.js closely in the Chrome Network panel. Is this possible a webpack issue where I need to optimize the bundle further?

    Reviewed by Nemsae at 2018-07-23 20:02
  • 12. Styled Components injects forwardRef in every component generating unecessary overhead

    Styled component injects forwardRef into every component, forwardRef adds an overhead and has considerably more impact on a Component's render time and JS thread time compared to a regular component, causing FPS drops, tha has been widely discussed here.

    I'm wondering if the styled-components' team is aware of that and if it'd be of your interest if I were to open a PR proposing removing forwardRef from the default implementation, making it optional.

    Reviewed by arthurgeron at 2022-05-07 23:37
  • 13. Git.io deprecation notice

    Hello, I've found that some of your files in this repo is still using https://git.io/, and this service will be discontinued in the future. (ref: Git.io deprecation) Theses files are: packages/styled-components/src/utils/error.ts

    This is an automated message from NPMMirror(https://github.com/npmmirror), a bot developed by Nova Kwok(https://github.com/n0vad3v).

    Reviewed by npmmirror at 2022-04-28 08:11
  • 14. refactor: replace `git.io` within error message

    All links on git.io will stop redirecting after April 29, 2022: https://github.blog/changelog/2022-04-25-git-io-deprecation/, replace all git.io usage with the original URL.


    Alternative solution: use https://styled-components.com/error#${code} for the redirection.

    Reviewed by SukkaW at 2022-04-26 14:43
  • 15. Cypress/Jest class name selection for styled components after the newer updates in next js

    I have quite a bit of legacy code in cypress which utilizes the random class names generated by styled components. The fact that we have used those classnames in our cypress codebase is because they didn't change until we got the newest Next.js release update. But after this update all the styled components classnames got updated and our whole automated regression test case codebase started failing. The obvious solution is that we have to add our custom classname or custom tag to the used jsx elements and tweak the whole cypress codebase. Is there any workaround so that we don't have to do that and make the previous classnames persist throughout any updates we get?

    Reviewed by aritra-ttt at 2022-04-25 20:37
  • 16. How to intercept children prop?

    I am building a button component as part of a UI kit. Ideally I can just export a styled component instead of a function component so that all the button html attributes pass through. However I want to intercept the children prop and run it through a function.

    export interface ButtonProps {
      children: React.ReactNode
      variant: 'primary' | 'danger' | 'neutral'
      size?: 'md' | 'sm'
      type: 'solid' | 'outline' | 'link'
    }
    
    export const Button = styled.button.attrs<ButtonProps>(props => ({...props, children: wrapStringChildren(props.children)}))<ButtonProps>`
      color: #fff;
    `
    

    I get this type error:

    Property 'children' does not exist on type 'never'.
      The intersection 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "key" | keyof ButtonHTMLAttributes<...>> & { ...; } & ButtonProps, any>' was reduced to 'never' because property 'type' has conflicting types in some constituents.ts(2339)
    

    I don't understand what this error means, but I am wondering if I am just trying to do something that is not possible? I get the sense .attrs was not designed to interact with react's children prop

    Reviewed by alexpaxton at 2022-04-12 18:51
CSS Maid ๐Ÿงน A tool made for React.js to clean up CSS default styling! Give your CSS a nice reset and style with less hassle!
CSS Maid ๐Ÿงน A tool made for React.js to clean up CSS default styling! Give your CSS a nice reset and style with less hassle!

CSS Maid ?? What is it? CSS Maid is a tool for React.js that helps clean up & reset default css! It resets default padding, remove text-decoration on

Sep 1, 2021
CSS style loader for Webpack that is optimized for isomorphic (universal) web apps.
CSS style loader for Webpack that is optimized for isomorphic (universal) web apps.

Isomorphic CSS style loader for Webpack CSS style loader for Webpack that works similarly to style-loader, but is optimized for critical path CSS rend

May 7, 2022
Style your React components with simplicity using css inside your comments.

Style your React components with simplicity using css inside your comments.

Oct 12, 2021
Court.css - A naive CSS Utility framework based on JSX and css custom properties

court.css ?? A (work in progress) JSX-based, CSS utility framework with a predic

Mar 14, 2022
๐ŸŽจ Aesthetic is an end-to-end multi-platform styling framework that offers a strict design system, robust atomic CSS-in-JS engine, a structural style sheet specification (SSS), a low-runtime solution, and much more!

Aesthetic Start using Aesthetic now! aestheticsuite.dev Aesthetic is an end-to-end, multi-platform styling and design suite, that offers the following

May 7, 2022
CSS-in-JS solution with style-to-state bindings, SSR, and a next-level developer experience.

A set of modules is for CSS-in-JS solution that includes state-to-style bindings, SRR and next-level developer experience. It includes a framework-agnostic implementation

Mar 23, 2022
๐Ÿ‘ฉโ€๐ŸŽค CSS-in-JS library designed for high performance style composition
๐Ÿ‘ฉโ€๐ŸŽค CSS-in-JS library designed for high performance style composition

emotion The Next Generation of CSS-in-JS Emotion 11 has been released ?? See the blog post Emotion is a performant and flexible CSS-in-JS library. Bui

May 14, 2022
Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation

Aphrodite Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation. Support for colocating y

May 10, 2022
Flexibly styled chat-widget for your react apps.
Flexibly styled chat-widget for your react apps.

Flexibly styled chat-widget for your react apps. It was mainly created for integration with chat-bots in messengers.

Jun 11, 2021
Parse CSS and add vendor prefixes to rules by Can I Use

Autoprefixer PostCSS plugin to parse CSS and add vendor prefixes to CSS rules using values from Can I Use. It is recommended by Google and used in Twi

May 18, 2022
Material-tailwind - An easy-to-use components library for Tailwind CSS and Material Design
Material-tailwind - An easy-to-use components library for Tailwind CSS and Material Design

Material-tailwind - An easy-to-use components library for Tailwind CSS and Material Design

May 10, 2022
Autoprefixer for JavaScript style objects

inline-style-prefixer A small, simple and fast vendor prefixer from JavaScript style object. Support Us Support Robin Frischmann's work on Fela and it

Feb 25, 2022
A tool for creating ratio-based style systems built in React.
A tool for creating ratio-based style systems built in React.

Rational Design is a tool for generating type-scales for greater consistency in design systems or web design projects. Itโ€™s built with React Hooks, SCSS, Webpack, and npm scripts, and is fully responsive.

Dec 29, 2021
A terminal style/styled portfolio website made with <3 using react.

A Terminal Styled Portfolio Website. ??โ€??, a terminal style/styled portfolio website made with <3 using react.

May 14, 2022
Encapsulated styling for your javascript components with all the power of javascript and CSS combined.

Stilr Encapsulated styling for your javascript components with all the power of javascript and CSS combined. Unique class names (Content Hash Based) U

May 7, 2021
Repositรณrio utilizado na criaรงรฃo de um setup para facilitar o inicio do desenvolvimento de apps com React, Next e TypeScript. Sรณ "clonar" e "codar"! hahaha

Template para desenvolvimento de projetos utilizando REACT e NEXT com TypeScript Como executar Clone o projeto e acesse a pasta do mesmo. $ git clone

Jan 7, 2022
This repository allows you to create a React template component folder. It optionally includes scss and css files

Generate-React-Components - grc grc let you generate react components in typescript in a folder you specify and it will include .tsx, .scss, .css file

Nov 26, 2021
Whirlwind is a utility-first styling framework specifically designed for React Native. It is heavily inspired by Tachyons and Tailwind CSS and uses low-level building blocks for rapidly building custom designs.

React Native Whirlwind ??๏ธ A utility-first CSS framework designed for React Native. Whirlwind is a utility-first CSS framework specifically designed f

May 6, 2022
CSS media queries in react - for responsive design, and more.

react-responsive Information Package react-responsive Description Media queries in react for responsive design Browser Version >= IE6* Demo The best s

May 12, 2022